Angular 在何处声明角捕获所有(未找到)路由
我有一个主Angular 在何处声明角捕获所有(未找到)路由,angular,routes,angular5,angular2-routing,angular-routing,Angular,Routes,Angular5,Angular2 Routing,Angular Routing,我有一个主app.routing.module.ts,如下所示: const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: '', redirectTo: '/home', pathMatch: 'full' } ]; @NgModule({ imports: [ RouterMo
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 {}
然后是两个子路由模块:
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 {}
我指的是“一网打尽”的路线:
{ path: '**', redirectTo: '/home', pathMatch: 'full' }
如果我把它放在AppRoutingModule
中,那么如果它不匹配AppRoutingModule
中定义的任何路由,它就会启动。例如,我无法转到https://myapp/DefRoute1
在deroutingModule
如果我把它放在AbcRoutingModule
中,那么所有本地路由都可以工作,但是DefRoutingModule
中的东西不工作
我应该把它放在哪里,这样只有当我的所有路由模块都无法匹配url时它才会匹配?确保
AppRoutingModule
(根路由模块)在模块导入中声明为最后一个。然后在其中声明catch-all通配符。文档链接:
问了这个问题后,我发现应该将根路由模块作为最后一个导入,这样可以修复它。
@NgModule({
declarations: [
//...
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
// all other modules including any child routing modules
// Last module
AppRoutingModule
],
providers: [
//..
],
bootstrap: [
//..
]
})
export class AppModule { }