ngrx effects error handling

ⅰ亾dé卋堺 提交于 2019-11-27 08:37:35

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

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.

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

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

The @Effect stream is completing when the error occurs, preventing any further actions.

The solution is to switch to a disposable stream. If an error occurs within the disposable stream it's okay, as the main @Effect stream always stays alive, and future actions continue to execute.

@Effect()
login$ = this.actions$
    .ofType('LOGIN')
    .switchMap(action => {

        // This is the disposable stream!
        // Errors can safely occur in here without killing the original stream

        return Rx.Observable.of(action)
            .map(action => {
                // Code here that throws an error
            })
            .catch(error => {
                // You could also return an 'Error' action here instead
                return Observable.empty();
            });

    });

More info on this technique in this blog post: The Quest for Meatballs: Continue RxJS Streams When Errors Occur

this is how I handle the option to be notified or not notified on Observables that didn't find any data:

 public listenCampaignValueChanged(emitOnEmpty: boolean = false): Observable<CampaignsModelExt> {
        var campaignIdSelected$ = this.ngrxStore.select(store => store.appDb.uiState.campaign.campaignSelected)
        var campaigns$ = this.ngrxStore.select(store => store.msDatabase.sdk.table_campaigns);
        return campaignIdSelected$
            .combineLatest(campaigns$, (campaignId: number, campaigns: List<CampaignsModelExt>) => {
                return campaigns.find((i_campaign: CampaignsModelExt) => {
                    return i_campaign.getCampaignId() == campaignId;
                });
            }).flatMap(v => (v ? Observable.of(v) : ( emitOnEmpty ? Observable.of(v) : Observable.empty())));
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!