有插座的Angular lazyload子路线

问题描述 投票:1回答:1

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

我试图完成的任务

我正在尝试使用动态参数的路由,并具有该参数的子路由。我希望这个模块是延迟加载的。我在路径定义中使用: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两者都应该在命名的router-outlet内加载 - 所以在这两种情况下UserComponent都应该加载。

当我尝试加载UserOtherComponent(或任何已定义的子路径)时,我得到此控制台输出:

错误错误:未捕获(承诺):错误:无法匹配任何路由。 URL段:'user / hello / other'错误:无法匹配任何路由。网址细分:'user / hello / other'

使用空子路由时,我没有控制台错误,但未加载UserComponent。在我自己的项目中(不是这个复制)我加载了UserComponent - 我似乎无法弄清楚为什么空路径在我自己的项目中有效。也许这些信息有帮助。

编辑:

在app组件中添加了缺少的路由器插座。现在我回到我在整个项目中遇到的确切问题。

路线user/user呈现UserDefaultContentComponent。 user/user/other仍然无法正常工作

angular angular-routing angular-router
1个回答
1
投票

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.