根据先前响应的结果进行顺序级联可观察到的对象,并将其重新映射到新的数据对象 [英] Sequential cascade Observables according result from previous response and remap to new data object

查看:102
本文介绍了根据先前响应的结果进行顺序级联可观察到的对象,并将其重新映射到新的数据对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用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更改为switchMap,以防内部可观察对象是连续流,并且当源可观察对象发出时,它也会取消内部可观察对象.

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

这篇关于根据先前响应的结果进行顺序级联可观察到的对象,并将其重新映射到新的数据对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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