Search code examples
angularangular-services

Sharing data service between components


I'm new in Angular and have a problem. I have two components A and B. And SharedDataService. In component A I get data from REST service and to share this data with component B I want to use SharedDataService.

Component A:

let data: Data;
this.restService.getData().subscribe(data => 
          {
            this.sharedService.addSharedData(data);
          } , error => console.error(error));

Component B:

let sharedData: Data;
     this.SharedService.getSharedData()
     .subscribe(ds => sharedData = ds);

And SharedService:

public sharedData: Data;

  constructor() { }

  addSharedData(data : Data) {
    this.sharedData = data;
  }

  getSharedData() : Observable<Data> {
    return of (this.sharedData);
  }

During debug I found out that Component B tries to get data several times earlier than Component A put there smth. How it works? I thought that subcribe always fetch data if it's changed. But why now it doesn't work?

P.S. Sharing data works well. For instance it works If I put this.sharedService.addSharedData(fakedata); before restService subscribtion in Component A


Solution

  • modify your SharedService to utilize BehaviorSubject and power of reactive programming.

      private sharedData: BehaviorSubject<Data> = new BehaviorSubject<Data>(null);
    
      addSharedData(data: Data) {
        this.sharedData.next(data);
      }
    
      getSharedData(): Observable<Data> {
        return this.sharedData.asObservable();
      }
    
    

    this way SharedService will keep track of your data seamlessly and notify all getSharedData() subscriptions whenever a new value arrives with addSharedData(data: Data)

    also by using BehaviorSubject instead of Subject any new subscriptions will receive last previous data. But be aware that until some data arrives with addSharedData method getSharedData will provide null value.