我無法使用模塊化路由正確處理 Angular 10 應用程式中的 404 頁。
我的代碼結構如下:
|> app
|-- app.module.ts
|-- app-routing.module.ts
|-- app.component{ts, spec.ts, scss, html}
|-> pages
|--- pages.module.ts
|--> home-page
|---- home-page.module.ts
|---- home-page-routing.module.ts
|---> home-page
|----- home-page.component{ts, spec.ts, scss, html}
|--> test-page
|---- test-page.module.ts
|---- test-page-routing.module.ts
|---> test-page
|----- test-page.component{ts, spec.ts, scss, html}
(截斷的)全域應用程式路由模塊具有如下配置的 404 處理程式:
...
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
// If the following line is not commented out,
// You are unable to navigate to either the 'Home' or 'Test' pages.
// { path: '**', component: PageNotFoundComponent },
];
...
我遇到的問題是 Angular 匹配全域 404 處理程式./app/app-routing.module.ts并決議為該路由。
這是一個簡短的 stackblitz,提供了我的經驗示例 (注意:Stackblitz 示例實際上運行的是 Ng12,而我們的應用程式運行的是 Ng10——兩者都表現出相同的行為)
我的目標是讓全域 404 處理程式或重定向作業,同時繼續保持我們在各自模塊路由檔案中定義的所有頁面路由。
這可以做到嗎,如果可以的話——怎么做?
uj5u.com熱心網友回復:
我查看了您的 Stackblitz,問題是AppRoutingModule在PagesModule.
您應該匯入第PagesModule一個,因為它們的路由具有更高的優先級。
imports: [
BrowserModule,
RouterModule,
FormsModule,
PagesModule,
AppRoutingModule,
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
另一個(更好的)解決方案是延遲加載模塊:
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{
path: '',
loadChildren: () =>
import('./pages/pages.module').then((m) => m.PagesModule),
},
{ path: '**', component: PageNotFoundComponent },
];
這樣您就不必將整個 PagesModule 匯入您的 AppModule。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361719.html
標籤:javascript 有角的 打字稿 角度路由器
上一篇:我將如何無損地對Reactjs物件陣列的prop進行排序?
下一篇:typedi建構式注入回傳未定義
