0

I'm having two subscriptions in my ngOnInit(), I'm using the result of the first sub in the second one like this:

 ngOnInit() {
    this.Context.state$.subscribe((site) => {
      this._siteId = site.id;
    });

    this.SummaryContext.state$.subscribe((summary) => {
      this._unityId = this.siteSummaryContext.getFromId(summary, this._siteId).unityId;
    });

}

the _siteId variable is declared globaly, but I can't use in the getFromId() method, it's undefined. what am I doing wrong ?

M.Maria
  • 111
  • 4
  • 19
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – R. Richards Oct 02 '20 at 22:31

1 Answers1

2

The Observables are asynchronous. When the state of SummaryContext is subscribed, the _siteId might be still not set.

You can combine those Observables together to make sure the _siteId is always available:

this.Context.state$
  .pipe(
     switchMap(site => {
         this._siteId = site.id;
         return this.SummaryContext.state$;
     })
  )
  .subscribe((summary) => {
      this._unityId = this.siteSummaryContext.getFromId(summary, this._siteId).unityId;
  });

You can change the order if needed.

critrange
  • 5,652
  • 2
  • 16
  • 47