gpt4 book ai didi

angular - 在哪里声明 Angular catch all (Not found) 路由

转载 作者:行者123 更新时间:2023-12-04 16:30:07 25 4
gpt4 key购买 nike

我有一个主要的 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 中定义的任何路由,它就会启动。例如,我无法转到在 DefRoutingModule

中定义的 https://myapp/DefRoute1

如果我把它放在 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 { }

关于angular - 在哪里声明 Angular catch all (Not found) 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49914545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com