且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Angular2异步管道进行错误处理

更新时间:2023-12-01 21:14:28

是的,你是正确的关于捕获操作符和错误发生后做某事的能力...

Yes you're right regarding the catch operator and the ability to do something after errors occur...

我将利用 catch 操作符来捕获错误并执行某些操作:

I would leverage the catch operator to catch the error and do something:

const stream = Observable.interval(1000)
  .take(5)
  .map(n => {
    if (n === 3) {
      throw Observable.throw(n);
    }
    return n;
  })
  .catch(err => {
    this.error = error;
    (...)
  });

在模板中:

<div>{{error}}</div>

为了能够进行初始观察,您需要创建一个从点开始的新的发生错误:

To be able to go on the initial observable, you need to create a new one starting at the point where the error occurs:

createObservable(i) {
  return Observable.interval(1000)
    .range(i + 1, 5 - i)
    .take(5 - i)
  });
}

并在 catch callback:

and use it in the catch callback:

  .catch(err => {
    this.error = error;
    return this.createObservable(err);
  });

这两个问题可以帮助您:

These two questions could help you:

  • How to resumeOnError (or similar) in RxJS5
  • RxJS Continue Listening After Ajax Error (last answer)