I have a resolver that needs to fetch data from two dependant Apis before the page is loaded. The second call is defined by the result of the first one, so I try to chain the two observables and need to return the second one at the end of the resolver.
Before I tried to chain the observables I had:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<MySecondObservable> {
const observable1 = this.myService.getFirstDataSet();
observable1.subscribe(
firstDataSet => this.myService.firstDataSet = firstDataSet;
);
const observable2 = this.myService.getSecondDataSet(); // this requires data from firstDataSet
observable2.subscribe(
secondDataSet => this.myService.secondDataSet = secondDataSet;
);
return observable2;
}
This is obvioulsy wrong, when I try to apply some RxJs methods to pipe these observables I get an error in the second observable call saying that the firstDataSet is not defined. Here is what I got so far:
return observable1.pipe(
tap( firstDataSet => this.myService.firstDataSet = firstDataSet),
mergeMap( () => observable2.pipe(
tap(secondDataSet => this.myService.secondDataSet = secondDataSet
)
)
)
At each observable final result I want to store the received data into the service hence the tap()
. There is an overwhelming amount of documentation on RxJS, at the point that I found it difficult as a beginner to find what I want.
Any help is appreciated!
EDIT:
I modified the code to as suggested, but I still get an error.
const observable2 = this.myService.getSecondDataSet();
This method requires the firstDataSet to be resolved in order to work. However the console log that myService.firstDataSet
is undefined.