首页 > 解决方案 > 带插座的角度延迟加载子路由

问题描述

我试图在stackblitz中重现我的错误

我试图完成的事情

我正在尝试使用带有动态参数的路线,并拥有该参数的子路线。我希望这个模块被延迟加载。我已经使用:id路由定义中的定义为动态参数制定了一个可行的解决方案。

我希望子路由在不同的路由器插座中输出。

具体来说,我希望在路由上加载一个UserComponent组件(但总是加载- 示例user/:username:usernameUserDefaultContentComponentUserComponentuser/some-user/otherUserOtherComponentUserComponentuser/:usernameuser/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还是不行

标签: angularangular-routingangular-router

解决方案


你忘记<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>

在此处输入图像描述


推荐阅读