How do I pass data to Angular routed components?

前端 未结 16 1083
挽巷
挽巷 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:39

    I think since we don't have $rootScope kind of thing in angular 2 as in angular 1.x. We can use angular 2 shared service/class while in ngOnDestroy pass data to service and after routing take the data from the service in ngOnInit function:

    Here I am using DataService to share hero object:

    import { Hero } from './hero';
    export class DataService {
      public hero: Hero;
    }
    

    Pass object from first page component:

     ngOnDestroy() {
        this.dataService.hero = this.hero; 
     }
    

    Take object from second page component:

     ngOnInit() {
        this.hero = this.dataService.hero; 
     }
    

    Here is an example: plunker

提交回复
热议问题