首页 文章

在lettable rxjs运算符的组合管道中捕获错误

提问于
浏览
19

我们刚刚将其中一个应用程序升级到Angular 5,并开始转换为rxjs v5.5中引入的lettable operators .

因此,我们使用 .pipe() 运算符将可观察的管道重写为新语法 .

我们之前的代码看起来像这样,在 .switchMap() 中有一个 .catch() ,如果抛出错误就不会中断效果的运行 .

@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.map((action: LoadData) => action.payload)
.withLatestFrom(this.store.select(getCultureCode))
.switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)
  .map(result => {
    if (!result) {
      return new LoadDataFailed('Could not fetch data!');
    } else {
      return new LoadDataSuccessful(result);
    }
  })
  .catch((err, caught) => {
    return Observable.empty();
  });
  );

如果在调用 dataService 时抛出错误,它将被捕获并处理(简化了此处的错误处理) .

使用 .pipe() 的新语法和使用,我们现在有了这个

@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.pipe(
  map((action: LoadData) => action.payload),
  withLatestFrom(this.store.select(getCultureCode)),
  switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)),
  map(result => {
    if (!result) {
      return new LoadDataFailed('Could not fetch data!');
    } else {
      return new LoadDataSuccessful(result);
    }
  })
  );

我怎样才能以类似的方式使用新语法捕获可观察管道中的任何抛出错误?

1 回答

  • 29

    重构后,您将 map 移出 switchMap 投影,因此任何错误都将关闭外部流 . 要保持两个流等效,您需要在投影本身中使用 pipe ,如下所示:

    import { empty } from 'rxjs;
    
    // ...
    
    @Effect()
    loadData$ = this.actions$
    .ofType(LOAD_DATA)
    .pipe(
      map((action: LoadData) => action.payload),
      withLatestFrom(this.store.select(getCultureCode)),
      switchMap(([payload, cultureCode]) =>
        this.dataService.loadData(payload, cultureCode)
          .pipe(
             map(result => {
               if (!result) {
                 return new LoadDataFailed('Could not fetch data!');
               } else {
                 return new LoadDataSuccessful(result);
               }
              }),
             catchError((err, caught) => {
               return empty();
             })
          )
      )
    );
    

相关问题