通过传递引起错误的值可观察的flatMap转换错误处理

时间:2019-06-24 22:08:34

标签: angular rxjs angular2-observables

场景: 服务需要加载会员信息。为此,它需要1)加载成员的ID,以及2)加载详细信息。步骤1是强制性的(如果失败,则整个过程应返回错误),步骤2是可选的(如果失败,则返回仅具有id的记录)。

环境:Angular 6,打字稿

代码:

                               perCent              
              Antibiotic        AMPICI        BENZYL
                Organism                            
0     Enterococcus avium     0.0 (0/1)     0.0 (0/1)
1    Enterococcus cassel   100.0 (1/1)   100.0 (1/1)
2  Enterococcus faecalis  95.7 (44/46)  95.6 (43/45)
3  Enterococcus faecalis   100.0 (2/2)   100.0 (2/2)

我想“ flatMap”对我来说是正确的转换,因为我正在尝试将member-id转换为完整的member-info。但是,我不知道如何从成功完成的public getMemberId() : Observable<string> { .. doing some http request ...} public getMemberInfo(memberId : int) : Observable<Member> { ... some code ... return new Member(loaded_id, loaded_name); } // expected final usage: loadUser().subscribe( res => ... at least member-id was loaded err => ... member-id was not loaded ) // the not-working implementation: public loadUser() : Observable<Member> { this.getMemberId().pipe( flatMap(id => getMemberInfo(id)), catchError(err => new Member(id, "John Doe")) // how to get 'id' here?? } 函数中获取id,并在getMemberId()失败时将其作为参数传递到catchError块中。 getMemberInfo()仅将错误对象作为参数,但是我需要以某种方式访问​​上层Observable的结果。

1 个答案:

答案 0 :(得分:0)

您应该像这样catchError进入内部观察

this.getMemberId()
        .pipe(
          mergeMap(id => {
              return this.getMemberInfo(id)
                        .pipe(
                          catchError(error => {
                            return new Member(id, "John Doe")) // how to get 'id' here??
                          });
              })
          );

在内部观察中使用catchError将使id在返回Member实例时可用。