[英]How to use angular 6 Route Auth Guards for all routes Root and Child Routes?
[英]Angular wildcard route replacing child routes
我有一個名為“host”的模塊,它有自己的路由,我想插入app-routing.module。 但是,我首先遇到通配符加載問題並顯示PageNotFoundComponent,而不是主機組件加載。 我有以下文件。
host.module.ts
....
const routes: Routes = [
{
path: 'host',
children: [
{ path: '', component: HostComponent }
]
}
];
@NgModule({
declarations: [HostComponent],
imports: [
CommonModule,
RouterModule.forChild(routes)
]
})
export class HostModule { }
APP-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent, pathMatch: "full"},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts
@NgModule({
declarations: [
AppComponent,
HomeComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HostModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<h2>Home</h2>
<ul>
<li>
<h2><a routerLink="/host">host</a></h2>
</li>
</ul>
<router-outlet></router-outlet>
問題:當我運行應用程序並單擊“主機”按鈕時,它會加載PageNotFoundComponent。 我顯然希望它轉到HostComponent。
在app.module.ts
您需要重新排序導入
@NgModule({
declarations: [
AppComponent,
HomeComponent,
PageNotFoundComponent
],
imports: [
BrowserModule,
HostModule, <--- this before AppRoutingModule
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
原因是因為配置中的路由順序很重要。 https://angular.io/guide/router#configuration
最后一條路徑中的**路徑是通配符。 如果請求的URL與配置中先前定義的路由的任何路徑不匹配,路由器將選擇此路由。 這對於顯示“404 - 未找到”頁面或重定向到另一個路徑非常有用。
配置中的路由順序很重要,這是設計的。 路由器在匹配路由時使用第一匹配勝利策略,因此應將更具體的路由放置在不太具體的路由之上。 在上面的配置中,首先列出具有靜態路徑的路由,然后列出與默認路由匹配的空路徑路由。 通配符路由是最后一個,因為它匹配每個URL,只有在沒有其他路由首先匹配時才應選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.