在Angular 2中直接访问延迟加载的模块子路由时出错

时间:2018-05-08 03:17:14

标签: angular angular-routing angular-router

以下是示例:https://stackblitz.com/edit/angular-xvmi8t

我在基础应用程序模块中使用loadChildren为子路由添加了这个延迟加载模块,并且在构造此模块时动态设置此延迟加载模块的子路由:

@NgModule({
  imports: [RouterModule.forChild([]), CommonModule],
  declarations: [LazyComponent, TestComponent, DefaultComponent],
  entryComponents: [LazyComponent, TestComponent, DefaultComponent]
})
export class LazyModule {
  constructor(private router: Router) {
    const config: Route = router.config.find(r => r.path === 'lazypage');
    if (config) {
      config.children = [
        {
          path: '', component: LazyComponent, children: [
            {
              path: 'itemA', children: [
                { path: 'item1', component: TestComponent },
                { path: 'item2', component: TestComponent },
                { path: '', component: DefaultComponent }
              ]
            },
            {
              path: 'itemB', children: [
                { path: 'item1', component: TestComponent },
                { path: 'item2', component: TestComponent },
                { path: '', component: DefaultComponent }
              ]
            },
            {
              path: 'itemC', children: [
                { path: 'item1', component: TestComponent },
                { path: '', component: DefaultComponent }
              ]
            },
            {
              path: '', component: DefaultComponent
            }
          ]
        }
      ];
    }
  }

}

如果我访问首先加载这个延迟加载的模块然后访问其中一个子路径的子路由,它工作正常。但是当我第一次直接访问其中一个子路径时(通过直接URL输入)抛出异常。我想知道为什么以及如何解决这个问题?

0 个答案:

没有答案