Angular 2: getting RouteParams from parent component

前端 未结 13 959
暖寄归人
暖寄归人 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:03

    Passing Injector instance to constructor in child component may not be good if you want to write unit tests for your code.

    The easiest way to work around this is to have a service class in the parent component, in which you save your required params.

    @Component({
        template: `
    `, directives: [RouterOutlet], providers: [SomeServiceClass] }) @RouteConfig([ {path: "/", name: "IssueList", component: IssueListComponent, useAsDefault: true} ]) class IssueMountComponent { constructor(routeParams: RouteParams, someService: SomeServiceClass) { someService.id = routeParams.get('id'); } }

    Then you just inject the same service to child components and access the params.

    @Component({
        template: `some template here`
    })
    class IssueListComponent implements OnInit {
        issues: Issue[];
        constructor(private someService: SomeServiceClass) {}
    
        getIssues() {
            let id = this.someService.id;
            // do your magic here
        }
    
        ngOnInit() {
            this.getIssues();
        }
    }
    

    Note that you should scope such service to your parent component and its child components using "providers" in parent component decorator.

    I recommend this article about DI and scopes in Angular 2: http://blog.thoughtram.io/angular/2015/08/20/host-and-visibility-in-angular-2-dependency-injection.html

提交回复
热议问题