Angular 2: sharing data across different routes

前端 未结 3 995
死守一世寂寞
死守一世寂寞 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

    0 讨论(0)
  • 2021-02-15 12:04

    What do you think about NgRx solution inspired by Redux? You can read more there - https://github.com/ngrx/store

    You will have a single application store, which can be subscribed in the proper components. So - you could just dispatch an event before route changed. This soulution use only reducers, so in different ways than using store, your data would be immutable - this is the next advantage.

    0 讨论(0)
  • 2021-02-15 12:14

    I'm not sure if the is is what you're after but if you need to share data across sibling routes you could try this.

    Create a module Import and Declare the service in the module

    import { MyService } from './my.service’;
    
    @NgModule({
      ...
      providers: [
        MyService
      ]
      …
    })
    

    Declaring the the service in the module route means we can then pass the service by reference to the child routes. Do not use the service in the parent component

    In the child route components, import the service

    import { MyService } from '../my.service’;
    

    In each component where the service should be used, do not add the service to the components metadata because we’ve already added it to the module definition. Add the service to the component constructor

    export class MyChildRouteComponent implements OnInit {  
    ...
     constructor(
        private _myService: MyService,
        private _router: Router
      ) { }
     ...
    }
    

    If you then set a service property in one child route component, you will then be able to get it from a sibling child component.

    0 讨论(0)
提交回复
热议问题