可出租rxjs运算符的组合管道中捕获错误 [英] Catch error in combined pipe of lettable rxjs operators

查看:71
本文介绍了可出租rxjs运算符的组合管道中捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们刚刚将其中一个应用程序升级到Angular 5,并开始过渡到可操作运算符(在rxjs v5.5中引入).

We've just upgraded one of our applications to Angular 5, and started to transition into lettable operators as introduced in rxjs v5.5.

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

Because of this, we have rewritten our observable pipelines to the new syntax with the .pipe() operator.

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

Our previous code would look like this, with a .catch() inside the .switchMap() as to not interrupt the running of effects if an error is thrown.

@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 的调用中引发错误时,将捕获并处理该错误(此处简化了错误处理).

In the case of an error thrown in the call to the dataService it would be caught and handled (simplified the error handling here).

使用新语法并使用 .pipe(),我们现在有了

With the new syntax and use of .pipe(), we now have this

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

如何使用新语法以类似的方式在可观察的管道中捕获所有抛出的错误?

How can I in a similar fashion catch any thrown errors in the observable pipeline, using the new syntax?

推荐答案

重构后,您将 map switchMap 投影中移出了,所以任何错误都会关闭外部流.为了使两个流保持相等,您需要像这样在投影本身中使用 pipe :

After refactoring you moved map out of switchMap projection, so any error will close the outer stream. To keep both streams equivalent, you need to use pipe in the projection itself like that:

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

这篇关于可出租rxjs运算符的组合管道中捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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