【发布时间】:2019-03-12 11:33:35
【问题描述】:
我试图在stackblitz 中重现我的错误
我试图完成的事情
我正在尝试使用带有动态参数的路线,并拥有该参数的子路线。我希望这个模块被延迟加载。
我已经使用路由定义中的:id 定义为动态参数制定了一个可行的解决方案。
我希望子路由在不同的路由器插座中输出。
具体来说,我想在路由user/:username 上加载一个组件(UserComponent) - 如果在:username 之后路径为空,我想在UserComponent 内定义的路由器中加载UserDefaultContentComponent - 如果路径的扩展名为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(或任何定义的子路径)时,我得到了这个控制台输出:
ERROR 错误:未捕获(在承诺中):错误:无法匹配任何路由。 URL 段:'user/hello/other' 错误:无法匹配任何路由。 URL 段:'user/hello/other'
虽然子路由为空,但我没有收到控制台错误,但未加载 UserComponent。在我自己的项目(不是这个复制品)中,我加载了 UserComponent - 我似乎无法弄清楚为什么空路径在我自己的项目中有效。也许这些信息会有所帮助。
编辑:
在应用组件中添加了缺少的路由器插座。现在我回到了我在整个项目中遇到的确切问题。
路由 user/user 呈现 UserDefaultContentComponent。 user/user/other 还是不行
【问题讨论】:
-
对于初学者,您缺少
<router-outlet>app.component.html
标签: angular angular-routing angular-router