lah*_*rah 2 routes angular-routing angular2-routing angular angular5
我有一个主要的app.routing.module.ts:
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 {}
Run Code Online (Sandbox Code Playgroud)
然后是几个子路由模块:
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 {}
Run Code Online (Sandbox Code Playgroud)
我将此称为捕获所有路线:
{ path: '**', redirectTo: '/home', pathMatch: 'full' }
Run Code Online (Sandbox Code Playgroud)
如果我把它放在 中AppRoutingModule,那么如果它与AppRoutingModule. 例如,我无法转到https://myapp/DefRoute1中定义的DefRoutingModule
如果我把它放进去AbcRoutingModule,那么所有本地路线都有效,但里面的东西DefRoutingModule不起作用。
我应该把它放在哪里,这样它只会在我所有的路由模块都无法匹配 url 时匹配?
确保AppRoutingModule(根路由模块)在模块导入中最后声明。然后在那里声明 catch all 通配符。文档链接: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 { }
Run Code Online (Sandbox Code Playgroud)