Angular9 設(shè)置通配符路由

2020-07-06 16:56 更新

當(dāng)用戶試圖導(dǎo)航到那些不存在的應(yīng)用部件時(shí),在正常的應(yīng)用中應(yīng)該能得到很好的處理。要在應(yīng)用中添加此功能,需要設(shè)置通配符路由。當(dāng)所請(qǐng)求的 `URL 與任何路由器路徑都不匹配時(shí),Angular 路由器就會(huì)選擇這個(gè)路由。

要設(shè)置通配符路由,請(qǐng)?jiān)?routes 定義中添加以下代碼。

//AppRoutingModule (excerpt)


{ path: '**', component:  }

這兩個(gè)星號(hào) ** 告訴 Angular,這個(gè) routes 定義是通配符路由。對(duì)于 component 屬性,你可以使用應(yīng)用中的任何組件。常見(jiàn)的選擇包括應(yīng)用專屬的 PageNotFoundComponent,你可以定義它來(lái)向用戶展示 404 頁(yè)面,或者跳轉(zhuǎn)到應(yīng)用的主組件。通配符路由是最后一個(gè)路由,因?yàn)樗ヅ渌械?URL。有關(guān)路由順序的更多詳細(xì)信息,請(qǐng)參閱路由順序。

顯示 404 頁(yè)面

要顯示 404 頁(yè)面,請(qǐng)?jiān)O(shè)置一個(gè)通配符路由,并將 component 屬性設(shè)置為你要用于 404 頁(yè)面的組件,如下所示:

//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** 的最后一條路由是通配符路由。如果請(qǐng)求的 URL 與前面列出的路徑不匹配,路由器會(huì)選擇這個(gè)路由,并把該用戶送到 PageNotFoundComponent

設(shè)置重定向

要設(shè)置重定向,請(qǐng)使用重定向源的 path、要重定向目標(biāo)的 component 和一個(gè) pathMatch 值來(lái)配置路由,以告訴路由器該如何匹配 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 },
];

在這個(gè)例子中,第三個(gè)路由是重定向路由,所以路由器會(huì)默認(rèn)跳到 first-component 路由。注意,這個(gè)重定向路由位于通配符路由之前。這里的 path: '' 表示使用初始的相對(duì) URL( '' )。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)