简体   繁体   English

Resolver 中的链相关 Observables

[英]Chain Dependant Observables in Resolver

I have a resolver that needs to fetch data from two dependant Apis before the page is loaded.我有一个解析器,需要在加载页面之前从两个依赖的 API 中获取数据。 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.第二个调用是由第一个调用的结果定义的,所以我尝试链接两个 observables,并且需要在解析器的末尾返回第二个调用。

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.这是明显错误的,当我尝试将一些 RxJs 方法应用于 pipe 这些 observables 时,我在第二个 observable 调用中收到错误,说 firstDataSet 未定义。 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() .在每个可观察到的最终结果中,我想将接收到的数据存储到服务中,因此是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. RxJS 上有大量的文档,我发现作为初学者很难找到我想要的东西。 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.此方法需要解析 firstDataSet 才能工作。 However the console log that myService.firstDataSet is undefined.但是myService.firstDataSet未定义的控制台日志。

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:如果我正确理解了这个问题(您想进行 API 调用,等待它完成,然后根据结果发送另一个 API 请求),那么您需要使用switchMap运算符:

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

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM