延迟加载的路由基本URL行为异常

时间:2019-12-13 19:37:58

标签: angular ng-packagr

我创建了一个带有组件库的应用程序。我的图书馆包含路线。当我尝试将库延迟加载到应用程序中时,我使用以下路线:

const routes: Routes = [
  { path: 'test2', loadChildren: () => import('my-lib' ).then(x => x.MyLibModule) },
];

我将该路由导入到应用程序的AppRoutingModule中:

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})

在库模块MyLibModule中,我定义了库路由并使用forChild方法将其导入

imports: [
   ...
   RouterModule.forChild(routerConfig),
   ...
 ],

这适用于我的默认路由。如果导航到基本路由“ localhost:4200 / test2”,则库的默认路由会正确加载。但是,单击按钮并导航到另一条路线时,库路线的“ test2”库将被删除。将加载页面“ localhost:4200 / page2”,而不是“ localhost:4200 / test2 / page2”。该网址不存在,并且出现错误。但是,如果导航到“ localhost:4200 / test2 / page2”,则会加载正确的页面。

重定向时'test2'基本URL发生了什么?如何在不更改库中代码的情况下维护该基本URL?

1 个答案:

答案 0 :(得分:0)

更新19/12/13-使用relativeTo

1)在组件构造函数中注入ActivatedRoute

constructor(private router: Router, private route: ActivatedRoute) { }

2)Router.navigate()接受类型为NavigationExtras的第二个参数。使用注入的路由设置relativeTo属性。

this.router.navigate(['child'], {relativeTo: this.route});

StackBlitz demo