Angular Firebase-Cli Hosting Angular Router 2 Not Working

advertisements

I am trying to host an angular 2 app (created with angular cli) with Firebase but my routes are not working.

I created a project with angular 2 and typescript for a site I am working on where I want a static privacy-policy page.

When I perform

ng serve

and navigate to http://localhost:4200/privacy-policy in my browser I get the content I expect.

Here is the code as recommended by the angular 2 route page-

@NgModule({
    declarations: [
        AppComponent,
        HomeComponent,
        TermsOfServiceComponent,
        PrivacyPolicyComponent,
        PageNotFoundComponent
    ],
    imports: [
        AlertModule,
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot([
            {path: 'privacy-policy', component: PrivacyPolicyComponent},
            {path: 'terms-of-service', component: TermsOfServiceComponent},
            {path: '', component: HomeComponent},
            {path: '**', component: PageNotFoundComponent}
        ])
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

I configured Firebase hosting with my project here is my config file-

{
  "database": {
    "rules": "database.rules.json"
  },
  "hosting": {
    "public": "dist"
  }
}

To Deploy I run

ng build --prod
firebase deploy

When I navigate to https://MY-APP.firebaseapp.com/ The app loads fine for the default route.

However when I try to navigate to https://MY-APP.firebaseapp.com/privacy-policy I get 404.

I would have expected this to work as it did with ng serve.

Any help would be greatly appreciated.


In your app.module.ts file just add following things:

declare

import { LocationStrategy, HashLocationStrategy} from '@angular/common';

and in providers add following

   @NgModule({
        declarations: [...],
        imports:[...],
        providers:[..,{ provide: LocationStrategy, useClass: HashLocationStrategy },..]
        ...,
    })

Hope this will solve your problem.

And if possible keep your Routes in separate file.

Cheers