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.
Add a default routelink To make the application navigate to the dashboard automatically, add the following route to the routes array. content_copy { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, This route redirects a URL that fully matches the empty path to the route whose path is '/dashboard' .
The process of defining navigation element and the corresponding view is called Routing. Angular provides a separate module, RouterModule to set up the navigation in the Angular application.
At the basic level, routing allows angular to display different "pages" or components. You probably want to have it, if you want to navigate across pages in your application. It shouldn't hurt anything if you add it, but don't use it.
Late response, but since i faced the same problem today when i deployed my app on Firebase, here is the quick fix for it:
In your firebase.json file, update your hosting key by defining rewrite rules:
"hosting": { "public": "dist", "rewrites": [ { "source": "**", "destination": "/index.html" } ] }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With