[英]Angular lazyload child routes with outlet
我試圖在stackblitz 中重現我的錯誤
我試圖完成的事情
我正在嘗試使用帶有動態參數的路由,並具有該參數的子路由。 我希望這個模塊被延遲加載。 我已經使用路由定義中的:id
定義為動態參數制定了一個有效的解決方案。
我希望子路由在不同的路由器插座中輸出。
具體來說,我想的成分( UserComponent
裝載在路線) user/:username
-如果路徑是空的之后:username
我要加載UserDefaultContentComponent
在內部限定的路由器UserComponent
-如果路徑具有類似的擴展user/some-user/other
我希望UserOtherComponent
加載到插座中。 但始終在user/:username
上加載UserComponent
- 例如user/some-user
什么是打破這個的理論
因此,當我嘗試解析子路由時,我創建的配置出現錯誤。 我能夠在沒有延遲加載的情況下在空用戶路徑上加載UserComponent
。
我還認為將靜態子路由設置為動態:username
路由會導致問題。
配置
有關完整代碼,請參閱stackblitz
下面是我認為相關的代碼。 如果我在這里遺漏了什么,請發表評論:
應用路由(根路由)
const APP_ROUTES: Routes = [
{ path: '', component: AppComponent, data: { state: 'home' }},
{ path: 'user/:username', loadChildren: './user-module/user.module#UserModule'}
];
export const appRouting = RouterModule.forRoot(APP_ROUTES);
用戶路由(子路由)
const USER_ROUTES: Routes = [
{ path: '', component: UserComponent, children: [
{ path: '', component: UserDefaultContentComponent, outlet: 'user-outlet'},
{ path: 'other', component: UserOtherComponent, outlet: 'user-outlet'},
]}
];
export const userRouting = RouterModule.forChild(USER_ROUTES);
這些的導入在 UserModule 和 App 模塊中。 我還從用戶模塊導出子路由。
UserComponent - 包含命名的路由器插座:
<div>
THIS IS A USER
</div>
<router-outlet name="user-outlet"></router-outlet>
要測試的網址
這個 url 應該加載 UserOtherComponent: /user/hello/other
這個 url 應該加載 UserDefaultContentComponent: /user/hello
兩者都應該加載到命名的路由器出口 - 所以在這兩種情況下都應該加載 UserComponent。
當我嘗試加載 UserOtherComponent(或任何定義的子路徑)時,我得到了這個控制台輸出:
錯誤錯誤:未捕獲(承諾):錯誤:無法匹配任何路由。 URL 段:'user/hello/other' 錯誤:無法匹配任何路由。 URL 段:'用戶/你好/其他'
雖然使用空子路由,但我沒有收到控制台錯誤,但未加載 UserComponent。 在我自己的項目(不是這個復制品)中,我加載了 UserComponent - 我似乎無法弄清楚為什么空路徑在我自己的項目中有效。 也許這些信息有幫助。
編輯:
在應用程序組件中添加了缺少的路由器插座。 現在我又回到了我在整個項目中遇到的確切問題。
路由user/user
呈現 UserDefaultContentComponent。 user/user/other
仍然不起作用
您忘記在app.component.html
添加<router-outlet></router-outlet>
編輯 :
更新您的APP_ROUTES
const APP_ROUTES: Routes = [
{ path: '', component: HelloComponent, data: { state: 'home' }},
{ path: 'user', loadChildren: './user-module/user.module#UserModule'}
];
和您的USER_ROUTE
const USER_ROUTES: Routes = [
{ path: ':username', component: UserComponent, children: [
{ path: '', component: UserDefaultContentComponent},
{ path: 'other', component: UserOtherComponent},
]}
];
並替換
<router-outlet name="user-outlet"></router-outlet>
經過
<router-outlet></router-outlet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.