使用Angular2异步管道进行错误处理 [英] Error handling with Angular2 async pipe

查看:132
本文介绍了使用Angular2异步管道进行错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular2异步管道将值流式传输到DOM中。这是一个非常简单的例子:

I am using the Angular2 async pipe to stream values into the DOM. Here's a real simple example:

const stream = Observable.interval(1000)
  .take(5)
  .map(n => { if (n === 3) throw "ERROR"; return n; });

<div *ngFor="for num of stream | async">
  {{num}}
</div>

<div id="error"></div>

我想做的是让1-5的顺序显示,但是在错误项目(3),以某种方式填充 #error div与错误消息。

What I would like to do is to have the sequence of 1-5 displayed, but on the error item (3), somehow populate the #error div with the error message.

这似乎需要两件事:首先是角色异步管道能够做出有智慧的错误的能力,我看不到任何迹象。看看源代码,显然它会抛出一个JS异常,似乎不太友善。

This seems to require two things: first is the ability of the Angular async pipe to do something intelligent with errors, which I see no sign of. Looking at the source code, apparently it throws a JS exception, which doesn't seem too friendly.

其次是错误后重启或继续序列的能力。我已经阅读了关于 catch onErrorResumeNext 等等,但它们都涉及另一个序列,将被切换到错误。这使生成流的逻辑非常复杂,我只想在其中放置一系列数字(在这个简单的例子中)。我有沉没的感觉,一旦发生错误,游戏结束,观察完成,只能用不同的观察者重新启动。我还在学习可观察这实际上是这样吗?

Second is the ability to restart or continue the sequence after the error. I have read about catch and onErrorResumeNext and so on, but they all involve another sequence which will be switched to on an error. This greatly complicates the logic of generating the stream, on which I would just like to put a series of numbers (in this simple example). I have the sinking feeling that once an error occurs the game is over and the observable is completed and can only be "restarted" with a different observable. I'm still learning observables; is this in fact the case?

所以我的问题有两个:


  1. Angular2的异步管道可以做出一些聪明的错误吗?

  2. 可观察器有一些简单的方法在错误后继续吗?


推荐答案

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

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)

这篇关于使用Angular2异步管道进行错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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