Angular 2:从父组件获取RouteParams

Aic*_*ink 71 angular2-routing angular

如何从父组件获取RouteParams?

App.ts:

@Component({
  ...
})

@RouteConfig([
  {path: '/', component: HomeComponent, as: 'Home'},
  {path: '/:username/...', component: ParentComponent, as: 'Parent'}
])

export class HomeComponent {
  ...
}
Run Code Online (Sandbox Code Playgroud)

然后,在中ParentComponent,我可以轻松获取用户名参数并设置子路由.

Parent.ts:

@Component({
  ...
})

@RouteConfig([
  { path: '/child-1', component: ChildOneComponent, as: 'ChildOne' },
  { path: '/child-2', component: ChildTwoComponent, as: 'ChildTwo' }
])

export class ParentComponent {

  public username: string;

  constructor(
    public params: RouteParams
  ) {
    this.username = params.get('username');
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,如何在这些子组件中获得相同的"用户名"参数?做与上面相同的技巧,不会这样做.因为这些参数是在ProfileComponent中定义的还是什么?

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(
    public params: RouteParams
  ) {
    this.username = params.get('username');
    // returns null
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

Fáb*_*ira 63

更新:

现在Angular2 final正式发布,正确的方法如下:

export class ChildComponent {

    private sub: any;

    private parentRouteId: number;

    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        this.sub = this.route.parent.params.subscribe(params => {
            this.parentRouteId = +params["id"];
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}
Run Code Online (Sandbox Code Playgroud)

原版的:

以下是我使用"@ angular/router":"3.0.0-alpha.6"包的方法:

export class ChildComponent {

    private sub: any;

    private parentRouteId: number;

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

    ngOnInit() {
        this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
            this.parentRouteId = +params["id"];
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,路由具有以下格式:/ parent /:id/child /:childid

export const routes: RouterConfig = [
    {
        path: '/parent/:id',
        component: ParentComponent,
        children: [
            { path: '/child/:childid', component: ChildComponent }]
    }
];
Run Code Online (Sandbox Code Playgroud)

  • 你需要在**ngOnInit**中调用它(如图所示)而不是在构造函数中,因为我一开始就愚蠢地尝试过. (2认同)
  • 自 Angular 5.2 以来,有一种替代方法不需要您遍历 `parent` 1 次以上。不过,请参阅 /sf/answers/3395806151/ 仍然值得考虑此答案中的“订阅”/“取消订阅”模式。 (2认同)

Pro*_*oGM 9

你不应该尝试使用RouteParams你的ChildOneComponent.

RouteRegistry改用!

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(registry: RouteRegistry, location: Location) {
    route_registry.recognize(location.path(), []).then((instruction) => {
      console.log(instruction.component.params['username']);
    })
  }


  ...
}
Run Code Online (Sandbox Code Playgroud)

更新:从此拉取请求(角度β9):https://github.com/angular/angular/pull/7163

您现在可以在不使用的情况下访问当前指令recognize(location.path(), []).

例:

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(_router: Router) {
    let instruction = _router.currentInstruction();
    this.username = instruction.component.params['username'];
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过

更多详情:

https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta9-2016-03-09 https://angular.io/docs/ts/latest/api/router/Router-class html的

更新2: 从角度2.0.0.beta15开始的小变化:

现在currentInstruction不再是一个功能了.此外,您必须加载root路由器.(感谢@ Lxrd-AJ报道)

@Component({
  ...
})

export class ChildOneComponent {

  public username: string;

  constructor(_router: Router) {
    let instruction = _router.root.currentInstruction;
    this.username = instruction.component.params['username'];
  }

  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 稍微编辑一下这个答案,使用`_router.root.currentInstruction.component.params ['id']`.强调**root**,因为你现在从根路由器得到currentInstruction而不是`_router`.PS:我正在使用`angular2.0.0-beta.15` (3认同)

Lor*_*ing 7

如GünterZöchbauer所述,我使用https://github.com/angular/angular/issues/6204#issuecomment-173273143上的评论来解决我的问题.我使用Injectorangular2/core来获取父级的routeparams.原来角度2不能处理深层嵌套的路线.也许他们将来会添加它.

constructor(private _issueService: IssueService,
            private _injector: Injector) {}

getIssues() {
    let id = this._injector.parent.parent.get(RouteParams).get('id');
    this._issueService.getIssues(id).then(issues => this.issues = issues);
}
Run Code Online (Sandbox Code Playgroud)

  • 这在angular2 RC路由器上不再起作用. (8认同)

Yoh*_* G. 6

我找到了一个丑陋但有效的解决方案,通过请求父母(正是第二个祖先)注射器,并RouteParams从此处获取.

就像是

@Component({
  ...
})
export class ChildOneComponent {
  public username: string;

  constructor(injector: Injector) {
    let params = injector.parent.parent.get(RouteParams);

    this.username = params.get('username');
  }
}
Run Code Online (Sandbox Code Playgroud)