Chain Dependant Observables in Resolver

二次信任 提交于 2020-12-13 07:09:54

问题


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.


回答1:


If I understand the question correctly (you want to make an API call, wait for it to finish, then depending on the result, send another API request), then you need to use switchMap operator:

return observable1.pipe(
    tap( firstDataSet => this.myService.firstDataSet = firstDataSet),
    switchMap( observable1Result => observable2 ),
    tap(secondDataSet => this.myService.secondDataSet = secondDataSet)            

)


来源:https://stackoverflow.com/questions/65213856/chain-dependant-observables-in-resolver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!