ngrx效果错误处理 [英] ngrx effects error handling

查看:94
本文介绍了ngrx效果错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于@ngrx效果,我有一个非常基本的问题:如何忽略在效果执行期间发生的错误,以免影响以后的效果执行?

I have a very basic question concerning @ngrx effects: How to ignore an error that happens during the execution of an effect such that it doesn't affect future effect execution?

我的情况如下:我有一个动作(LOGIN)和一个监听该动作的效果.如果此效果内发生错误,我想忽略它.错误发生后第二次发送LOGIN时,应再次执行效果.

My situation is as follows: I have an action (LOGIN) and an effect listening to that action. If an error happens inside this effect, I want to ignore it. When LOGIN is dispatched a second time after this error, the effect should be executed a second time.

我第一次尝试这样做是

  @Effect()
  login$ = this.actions$
    .ofType('LOGIN')
    .flatMap(async () => {
      console.debug('LOGIN');
      // throw an error
      let x = [];x[0]();
    })
    .catch(err => {
      console.error('Error at login', err);
      return Observable.empty();
    });

分派LOGIN第一次抛出并捕获错误,与预期的一样.但是,如果此后第二次发送LOGIN,则什么也没有发生.效果没有执行.

Dispatching LOGIN the first time throws and catches the error, as expected. However, if I dispatch LOGIN a second time afterwards, nothing happens; the effect is not executed.

因此,我尝试了以下操作:

Therefore I tried the following:

    .catch(err => {
      return this.login$;
    });

,但这会导致无休止的循环...您知道如何在不防止事后执行效果的情况下捕捉错误吗?

, but this results in an endless loop... Do you know how to catch the error without preventing effect execution afterwards?

推荐答案

ngrx基础结构通过使用EffectsModule.run导入到应用程序NgModule中的提供程序来订阅效果.

The ngrx infrastructure subscribes to the effect via the provider imported into the app's NgModule using EffectsModule.run.

当可观察的错误且catch返回空的可观察对象时,组成的可观察对象完成,并且其订阅者被取消订阅-这是 可观察的合同 .这就是您看不到效果进一步处理LOGIN动作的原因.完成后将取消订阅该效果,并且ngrx基础结构不会重新订阅.

When the observable errors and catch returns a empty obervable, the composed observable completes and its subscribers are unsubscribed - that's part of the Observable Contract. And that's the reason you see no further handling of LOGIN actions in your effect. The effect is unsubscribed on completion and the ngrx infrastructure does not re-subscribe.

通常,您会在flatMap(现在称为mergeMap)内部进行错误处理:

Typically, you would have the error handling inside the flatMap (now called mergeMap):

import { Actions, Effect, toPayload } from "@ngrx/effects";

@Effect()
login$ = this.actions$
  .ofType('LOGIN')
  .map(toPayload)
  .flatMap(payload => Observable
    .from(Promise.reject('Boom!'))
    .catch(error => {
      console.error('Error at login', error);
      return Observable.empty();
    })
  });

组成内部可观察对象的catch会看到一个空的可观察对象被展平/合并到效果中,因此不会发出任何动作.

The catch composed into the inner observable will see an empty observable flattened/merged into the effect, so no action will be emitted.

这篇关于ngrx效果错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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