Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

When handling in NgRX Effect, the effect won't work anymore

For the life of me, I can't figure out why once and error is thrown and intercepted, the effect will not work anymore

  @Effect()
  register$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(RegisterAction),
      map(action => action.registrationInfo),
      mergeMap(registrationInfo => {
        return this.authService.createUser(registrationInfo.email, registrationInfo.password,
          registrationInfo.lastname, registrationInfo.firstname);
      }),
      map(credentialInfo => ProfileInitAction({credentialInfo})),
      catchError(error => [ProfileInitErrorAction(error)]),
    );
  });
question from:https://stackoverflow.com/questions/65838162/when-handling-in-ngrx-effect-the-effect-wont-work-anymore

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You know why? Because this is the normal workflow in RXJS. So an observable emits values at different times. When an error occurs, then the observable chain (or pipe or subscription, or what you want) breaks. You have a service call. This service call can fail, right? But you do this service call in a child observable chain. So you can handle the error in this child's observable chain, and this will not break your main observable chain. In one word, do the catchError in the mergeMap.

For example:

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { EMPTY } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { MoviesService } from './movies.service';

@Injectable()
export class MovieEffects {

  loadMovies$ = createEffect(() => this.actions$.pipe(
    ofType('[Movies Page] Load Movies'),
    mergeMap(() => this.moviesService.getAll() //< --- starting point of the child observable chain
      .pipe(
        map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
        catchError(() => EMPTY) // <--- this is runs in the child observable chain
      ))
    ) // <--- end of the child observable chain
  ); // <--- end of the main observable chain

  constructor(
    private actions$: Actions,
    private moviesService: MoviesService
  ) {}
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...