在子路线中保留路线参数?

时间:2018-03-15 12:13:56

标签: angular angular2-routing

在我的情况下,我有一些看起来像这样的路线。

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,因为它所做的只是向现有通用池添加新组件(重)。

所以GenericComponent将要求:id并且很好,但是SpecialComponent已经从参数中丢失了:id。身份证成了儿童路线。所以现在id为null,我无法加载/mock-server/thing/null

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

1 个答案:

答案 0 :(得分:1)

您可以在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}}
    ]
  }
];

在你的app.resolver中

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]

希望这对你有用祝你好运: - )

哦,是的,在你的Component.ts中,你有“id”:

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

我使用路线解析器的原因是它允许您在导航到新路线之前获取数据。