I have a main app.routing.module.ts
as so:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [
RouterModule.forRoot(routes),
],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
And then a couple of child routing modules:
const routes: Routes = [
{ path: 'AbcRoute1', component: AbcRoute1Component },
{ path: 'AbcRoute2', component: AbcRoute2Component }
];
@NgModule({
imports: [ RouterModule.forChild(routes) ],
exports: [ RouterModule ]
})
export class AbcRoutingModule {}
const routes: Routes = [
{ path: 'DefRoute1', component: DefRoute1Component },
{ path: 'DefRoute2', component: DefRoute2Component }
];
@NgModule({
imports: [ RouterModule.forChild(routes) ],
exports: [ RouterModule ]
})
export class DefRoutingModule {}
I am referring to this as the catch all route:
{ path: '**', redirectTo: '/home', pathMatch: 'full' }
If I put it in the AppRoutingModule
, then it kicks in if it doesn't match any routes defined in AppRoutingModule
. For example I am not able to go to https://myapp/DefRoute1
which is defined in DefRoutingModule
If i put it in AbcRoutingModule
, then all local routes work but stuff in DefRoutingModule
doesn't work.
Where do I put this so that it will only match if all my routing modules fail to match the url?
Ensure the AppRoutingModule
(the root routing module) is declared last in the Module imports. Then declare the catch all wildcard in there. Docs link: https://angular.io/guide/router#routing-module-order
@NgModule({
declarations: [
//...
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
// all other modules including any child routing modules
// Last module
AppRoutingModule
],
providers: [
//..
],
bootstrap: [
//..
]
})
export class AppModule { }