Angular 2: sharing data across different routes

前端 未结 3 988
死守一世寂寞
死守一世寂寞 2021-02-15 11:51

I have searched for similar questions in SO and I have not found any that addresses my specific case. There are many techniques to share data between angular components, and I h

3条回答
  •  不知归路
    2021-02-15 12:03

    use service that is provided by main application file and then inject it whenever you want to get/set data that will be available in whole app

    main.app.ts

    @Component({
    ...
      providers:[yourDataService]
    ...
    })
    

    other components

    import {yourDataService} from '...';
    
    @Component({
    ...
    providers:[]// we must use provider from main file
    ...
    })
    export class someComponent{
    
      contructor(private myData:yourDataService){}
    
    }
    

    it is important to use provider from main app file because if you provide service in each component you will have another instances of your service and of course different data in each service

    you can also use observables to be notified when some data has changed

    for more info look at hierarchical injections or tree injector

提交回复
热议问题