代码之家  ›  专栏  ›  技术社区  ›  user1059939

是否在子路由中保留路由参数?

  •  1
  • user1059939  · 技术社区  · 8 年前

    在我的例子中,我有一些像这样的路线。

    const appRoutes: Routes = [
       { 
           path: 'thing/:id',
           component: GenericComponent 
       },
       { 
           path: 'thing/special', 
           loadChildren: 'app/modules/thing/special.module#SpecialModule'
       }
    ];
    

    最终 SpecialModule 需要延迟加载,并且它有自己的子路由。目前,子路线是这样的:

    const specialRoutes: Routes = [
        {
            path: '',
            component: SpecialComponent
        }
    ];
    

    基本上, SpecialComponent 可能会扩展 GenericComponent 因为它所做的只是向现有的通用池中添加新组件(重)。

    所以 通用组件 将去请求 :id 很好,但是 特殊组件 已丢失 :id 从参数。该ID成为子路径。所以现在id为null,我无法加载 /mock-server/thing/null

    如何保留或访问丢失的 :id 在我的孩子路线参数中?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Frank Anneveld    8 年前

    您可以在ActiveRouteSnapshot上使用父级:

    route.parent.params['id']
    

    我的方法是在路由中使用解析器来获取子路由等的数据。。。在此示例中:IDResolver

    import { IDResolver } from '../../app.resolver';
    
    const routes: Routes = [
      {
        path: ':id',
        component: LayoutComponent,
        children: [
          {path: '', redirectTo: 'something', pathMatch: 'full'},
          {path: 'something', component: SomethingComponent, resolve: {IDResolver}}
        ]
      }
    ];
    

    在你的应用程序中。分解器

    import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/of';
    
    @Injectable()
    export class IDResolver implements Resolve<any> {
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return Observable.of(route.parent.params['id']);
      }
    }
    
    export const APP_RESOLVER_PROVIDERS = [
      IDResolver
    ];
    

    别忘了导入主模块

     providers: [APP_RESOLVER_PROVIDERS]
    

    祝你好运:-)

    哦,是的,在你的组件中。ts您的“id”带有:

      constructor(private route: ActivatedRoute) {
        route.snapshot.data.IDResolver.subscribe((result: any) => console.log(result.id));
      }
    

    我之所以使用路由解析程序,是因为它允许您在导航到新路由之前获取数据。