W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
當用戶試圖導航到那些不存在的應用部件時,在正常的應用中應該能得到很好的處理。要在應用中添加此功能,需要設置通配符路由。當所請求的 `URL 與任何路由器路徑都不匹配時,Angular 路由器就會選擇這個路由。
要設置通配符路由,請在 routes
定義中添加以下代碼。
//AppRoutingModule (excerpt)
{ path: '**', component: }
這兩個星號 **
告訴 Angular
,這個 routes
定義是通配符路由。對于 component 屬性,你可以使用應用中的任何組件。常見的選擇包括應用專屬的 PageNotFoundComponent
,你可以定義它來向用戶展示 404 頁面,或者跳轉到應用的主組件。通配符路由是最后一個路由,因為它匹配所有的 URL
。有關路由順序的更多詳細信息,請參閱路由順序。
要顯示 404
頁面,請設置一個通配符路由,并將 component
屬性設置為你要用于 404
頁面的組件,如下所示:
//AppRoutingModule (excerpt)
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
{ path: '', redirectTo: '/first-component', pathMatch: 'full' }, // redirect to `first-component`
{ path: '**', component: FirstComponent },
{ path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page
];
path
為 **
的最后一條路由是通配符路由。如果請求的 URL
與前面列出的路徑不匹配,路由器會選擇這個路由,并把該用戶送到 PageNotFoundComponent
。
要設置重定向,請使用重定向源的 path
、要重定向目標的 component
和一個 pathMatch
值來配置路由,以告訴路由器該如何匹配 URL
。
//AppRoutingModule (excerpt)
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
{ path: '', redirectTo: '/first-component', pathMatch: 'full' }, // redirect to `first-component`
{ path: '**', component: FirstComponent },
];
在這個例子中,第三個路由是重定向路由,所以路由器會默認跳到 first-component
路由。注意,這個重定向路由位于通配符路由之前。這里的 path: '' 表示使用初始的相對 URL( '' )。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: