Angular 2 new Router: How to get router parameters of a child component?

后端 未结 6 2046
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 19:53

In the latest version of @angular/router 3.0.0-rc.1 The way you get the parameters from a URL/route changed.

Based on this documentation yo

6条回答
  •  被撕碎了的回忆
    2021-01-01 20:12

    The child parameters are associated/stored with the child ActivatedRoute. They are not available on the parent's ActivatedRoute. So you first need to get the child's ActivatedRoute using getter firstChild or children.

    Then, the parent can either subscribe to child parameter changes:

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { ActivatedRoute }               from '@angular/router';
    import { Subscription }                 from 'rxjs/Subscription';
    
    export class ParentComponent implements OnInit, OnDestroy {
       private sub: Subscription;
       constructor(private route: ActivatedRoute) {}
       ngOnInit() {
          this.sub = this.route.firstChild.params.subscribe(
            params => console.log(params.id));
       }
       ngOnDestroy() {
          this.sub.unsubscribe();
       }
    }
    

    or it can get a snapshot of the child parameters:

    import { Component }      from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    
    export class ParentComponent {
       constructor(private route: ActivatedRoute) {}
       someMethod() {
          console.log(this.route.firstChild.snapshot.params.id);
       }
    }
    

    If you want to get all of the children (e.g., if you have multiple outlets), use ActivatedRoute.children or ActivatedRouteSnapshot.children to get an array of child ActivatedRoutes or child ActivatedRouteShapshots.

提交回复
热议问题