Angular 2: getting RouteParams from parent component

前端 未结 13 913
暖寄归人
暖寄归人 2020-11-28 04:47

How do I get the RouteParams from a parent component?

App.ts:

@Component({
  ...
})

@RouteConfig([
  {path: \'/\', component: HomeCompo         


        
13条回答
  •  执笔经年
    2020-11-28 05:11

    You shouldn't try to use RouteParams in your ChildOneComponent.

    Use RouteRegistry, instead!

    @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']);
        })
      }
    
    
      ...
    }
    

    UPDATE: As from this pull request (angular beta.9): https://github.com/angular/angular/pull/7163

    You can now access to the current instruction without recognize(location.path(), []).

    Example:

    @Component({
      ...
    })
    
    export class ChildOneComponent {
    
      public username: string;
    
      constructor(_router: Router) {
        let instruction = _router.currentInstruction();
        this.username = instruction.component.params['username'];
      }
    
      ...
    }
    

    I haven't tried it, yet

    Further details here:

    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

    UPDATE 2: A small change as from angular 2.0.0.beta15:

    Now currentInstruction is not a function anymore. Moreover, you have to load the root router. (thanks to @Lxrd-AJ for reporting)

    @Component({
      ...
    })
    
    export class ChildOneComponent {
    
      public username: string;
    
      constructor(_router: Router) {
        let instruction = _router.root.currentInstruction;
        this.username = instruction.component.params['username'];
      }
    
      ...
    }
    

提交回复
热议问题