Search code examples
angularangular2-services

Angular 2 save data in services


I have a set of sub components, all get a part of data from one other component. They only get data they need to display. Now I want to implement and service which requesting an server. For the request I needs an id that is saved in the main component. I do not want to give each sub component the id, so I try to save it in the service, where it is needed.

But if I call the service from an sub component the value is not set. How could I save the id global and make it reachable for the service?


Solution

  • Don't provide the service on every component. This way every component will get a different service instance. Instead provide it only in

    @NgModule({
    
      imports  : [BrowserModule],
      providers: [SharedService],
      ...
    })
    export class AppModule{}