angular - 带插座的角度延迟加载子路由
问题描述
我试图完成的事情
我正在尝试使用带有动态参数的路线,并拥有该参数的子路线。我希望这个模块被延迟加载。我已经使用:id
路由定义中的定义为动态参数制定了一个可行的解决方案。
我希望子路由在不同的路由器插座中输出。
具体来说,我希望在路由上加载一个UserComponent
组件(但总是加载- 示例user/:username
:username
UserDefaultContentComponent
UserComponent
user/some-user/other
UserOtherComponent
UserComponent
user/:username
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 (或任何定义的子路径)时,我得到了这个控制台输出:
ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。URL 段:'user/hello/other' 错误:无法匹配任何路由。URL 段:'user/hello/other'
虽然使用空子路由,但我没有收到控制台错误,但未加载 UserComponent。在我自己的项目(不是这个复制品)中,我加载了 UserComponent - 我似乎无法弄清楚为什么空路径在我自己的项目中有效。也许这些信息会有所帮助。
编辑:
在应用程序组件中添加了缺少的路由器插座。现在我回到了我在整个项目中遇到的确切问题。
该路由user/user
呈现 UserDefaultContentComponent。user/user/other
还是不行
解决方案
你忘记<router-outlet></router-outlet>
在你的app.component.html
编辑 :
更新你的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>
推荐阅读
- android - 如何关闭信息窗口
- javascript - 具有停止和回答问题功能的 JS 视频播放器
- android - 检测到使用圆形对象的opencv ArUco库
- c# - C# Npgsql,支持过程调用?
- laravel - Javascript 向 laravel 控制器发送数据
- kotlin - 是否可以将纯 Java 代码注入 Kotlin?
- java - 如何以编程方式检测项目何时在 RecyclerView 中可见?
- amazon-web-services - 如何在 AWS CodePipeline 中停止执行或为操作设置设置超时?
- r - dplyr:在 group_by() 之后在 summarise() 中使用自定义函数
- javascript - 从烧瓶应用程序中列出 css 和 javascript 路径