解析程序中链相关的可观察物 [英] Chain Dependant Observables in Resolver

查看:53
本文介绍了解析程序中链相关的可观察物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个解析器,需要在加载页面之前从两个相关的Apis中获取数据.第二个调用是由第一个调用的结果定义的,因此,我尝试链接两个可观察变量,并需要在解析器的末尾返回第二个.

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;
    }

这是显而易见的错误,当我尝试应用一些RxJs方法来管道这些可观察对象时,我在第二个可观察调用中收到一条错误消息,指出未定义firstDataSet.这是到目前为止我得到的:

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            
            ) 
        )
    )

在每个可观察的最终结果中,我想将接收到的数据存储到服务中,因此将 tap().关于RxJS的文档太多,以至于我觉得作为初学者很难找到想要的东西.感谢您的帮助!

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!

我已按照建议将代码修改为,但仍然出现错误.

I modified the code to as suggested, but I still get an error.

const observable2 = this.myService.getSecondDataSet();

此方法需要解析firstDataSet才能起作用.但是,控制台日志中未定义 myService.firstDataSet .

This method requires the firstDataSet to be resolved in order to work. However the console log that myService.firstDataSet is undefined.

推荐答案

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

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)            

)

这篇关于解析程序中链相关的可观察物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆