根据先前响应的结果顺序级联 Observables 并重新映射到新的数据对象 [英] Sequential cascade Observables according result from previous response and remap to new data object
问题描述
我在使用 Observables
即 RxJs 6
的强大功能时遇到困难来正确地pipe、tap、map、mergemap
或任何我的 HttpClient
请求.具有所有不同功能的版本地狱使它不是很容易......
I have difficulties using the power of Observables
i.e. RxJs 6
to correctly pipe, tap, map, mergemap
or whatever my HttpClient
requests. The version hell with all the different functions makes it not very easy...
所以我需要首先进行 REST 调用,然后根据结果可能进行第二次 REST 调用并将可能收到的两个数据对象映射到一个新数据对象中.该函数应该返回一个 Observable
.
So what I need is to first make a REST call, then depending on the result probably do a second REST call and map the potentially two received data objects in one new data object. The function should return an Observable
.
所以目前,我使用 subject
解决了这个问题,我可以手动/按顺序完成我需要的操作.在这种情况下,该函数返回一个 Subject
,而不是 Observable.但是由于调用者只是订阅了这个函数,所以它可以工作.值得一提的是,下面的两个服务函数(userService.loadUserDetails()
和 adminService.getAdminData()
)只返回它们从 HttpClient
获得的可观察值.
So currently, I solved it with a subject
that I am be able to do manually / sequentially what I need. The function returns a Subject
, not an Observable in this case. But since the caller just subscribes to this function, it works.
To mention is that the two service functions below (userService.loadUserDetails()
and adminService.getAdminData()
) just returns observables they get from HttpClient
.
那么谁能帮我将下面的示例代码翻译成典型的 RxJs 6 代码?
So can anybody help me translate this example code below into typically RxJs 6 code?
myFunction(): Observable<any> {
const s = new Subject();
let obj: any = {};
this.userService.loadUserDetails().subscribe((userDetails) => {
obj.user = userDetails;
if (userDetails.authorities.includes('ADMIN')) {
this.adminService.getAdminData().subscribe((adminData) => {
obj.adminData = adminData;
s.next(obj);
s.complete();
});
} else {
s.next(obj);
s.complete();
}
});
return s;
}
推荐答案
使用 mergeMap
链接并有条件地返回
Use mergeMap
to chain and return conditionally
更新:将mergeMap更改为switchMap Incase内部observable是一个连续的流,当源observable发出时它也会取消内部observable.
Update: changed mergeMap to switchMap Incase inner observable is a continuous stream and when source observable emit it will also cancel the inner observable .
this.userService.loadUserDetails().pipe(
switchMap(user=>
user.authorities.includes('ADMIN')) ?
this.adminService.getAdminData().map(adminData=>({adminData,user})):
Observable.of({user}))
)
.subscribe();
这篇关于根据先前响应的结果顺序级联 Observables 并重新映射到新的数据对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!