How do I pass data to Angular routed components?

前端 未结 16 1337
挽巷
挽巷 2020-11-22 08:03

In one of my Angular 2 routes\'s templates (FirstComponent) I have a button

first.component.html

16条回答
  •  借酒劲吻你
    2020-11-22 08:26

    update 4.0.0

    See Angular docs for more details https://angular.io/guide/router#fetch-data-before-navigating

    original

    Using a service is the way to go. In route params you should only pass data that you want to be reflected in the browser URL bar.

    See also https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

    The router shipped with RC.4 re-introduces data

    constructor(private route: ActivatedRoute) {}
    
    const routes: RouterConfig = [
      {path: '', redirectTo: '/heroes', pathMatch : 'full'},
      {path : 'heroes', component : HeroDetailComponent, data : {some_data : 'some value'}}
    ];
    
    class HeroDetailComponent {
      ngOnInit() {
        this.sub = this.route
          .data
          .subscribe(v => console.log(v));
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
    

    See also the Plunker at https://github.com/angular/angular/issues/9757#issuecomment-229847781

提交回复
热议问题