代码之家  ›  专栏  ›  技术社区  ›  M'sieur Toph'

Angular 5-在组件内部获取懒散加载的模块根路径

  •  0
  • M'sieur Toph'  · 技术社区  · 6 年前

    有没有办法知道懒散加载模块的完整根路径 在…内 是吗?

    假设我有一个懒散的模块,名为 ParentModule ,以及以下范围内的两条可用路线: child1/{id1} child2/{id2}

    以下是我的路线声明:

    // AppRoutingModule
    
    const routes: Routes = [
      { path: 'parent', loadChildren: './parent/parent.module#ParentModule' },
      ...
    ];
    
    // ParentRoutingModule
    
    const routes: Routes = [
      { path: '', component: ParentComponent, children: [
        { path: 'child1/:id1', component: Child1Component},
        { path: 'child2/:id2', component: Child2Component}
      ] },
      { path: '**', redirectTo: '', pathMatch: 'full'}
    ];
    

    当我在lazyloaded模块ParentModule中时,我不知道导致它的url。ParentModule对 '/parent' 在ApprovingModule内设置upper。

    我的问题是我想在ParentModule内部导航(从Parent到childs 使用唯一的命令行(在通用 父模块 的组件)。

    所以我想用

    this._router.navigate(['child1', id1], {relativeTo: <?theFamousLazyModuleRootRoute?>});
    

    this._router.navigate([<?theFamousLazyModuleRootRoute?>, 'child1', id1]);
    

    但是如何知道这个根路径呢? 有人有想法动态获取这些信息吗?

    谢谢你提供的一切帮助。

    2 回复  |  直到 6 年前
        1
  •  0
  •   M'sieur Toph'    6 年前

    在具有“本地”绝对路径的懒散模块中导航的方法是使用 this._activatedRoute.parent

    this._router.navigate(['child1', id1, {relativeTo: this._activatedRoute.parent})
    

    在我的情况下,我想这是可行的,因为我在ParentModule路径下只有一个级别的导航:

    const routes: Routes = [
      { path: '', component: ParentComponent, children: [
        { path: 'child1/:id1', component: Child1Component},
        { path: 'child2/:id2', component: Child2Component}
      ] },
      { path: '**', redirectTo: '', pathMatch: 'full'}
    ];
    

    所以我可以使用 这个_激活路线。父母亲 模块中的每一个地方都可以找到根 activatedRoute 模块的。

    如果模块导航中有复杂的嵌套管线,则此操作可能不起作用。我没有测试。

        2
  •  -1
  •   Fateh Mohamed    6 年前

    在lazyLoading中,您不需要知道在子级之间导航的完整路径,您可以使用相对导航和../要在路径中上升一级,如果使用绝对路径,则需要在所有组件中进行更改,以防父管线发生更改

    假设你在

      /child1/add
    

    您想导航到

     /child/list/view/101
    

    你试试这个

      constructor(private route: ActivatedRoute,
        private router: Router) { } 
    ...
    
    this.router.navigate([ '../list/view', id ], { relativeTo: this.route });
    

    要在父级之间导航,可以使用绝对导航

    如果需要当前url,请尝试以下操作:

    this.router.url;