Search code examples
angularngrxngrx-storengrx-effectsngrx-store-4.0

Ngrx @Effects - Make it stop immediately


I have the following ngrx effect. Inside "map" I have a condition. How can I stop the effect immediately without continue to the mergeMap.

@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
  ofType('INIT_ACADEMY_DOMAIN'),
  map((action: any) => {
    const url = 'http://www.academy.xyzq';
    if (1 === 1) {
      // Make this effect stop immediately and do nothing more
    }
    action.url = url;
    return action;
  }),
  mergeMap((action: any) =>
    this.http.get(action.url).pipe(
      switchMap((data: any) => {
        return [{
          type: 'INIT_ACADEMY',
          payload: {
            academy: data.academy
          }
        }];
      })
    )),
  catchError(() => of ({
    type: 'INIT_IT_FAILED'
  }))
);


Solution

  • You can try like this.
    
    @Effect()
    myEffect$: Observable < Action > = this.actions$.pipe(
      ofType('INIT_ACADEMY_DOMAIN'),
      map((action: any) => {
        const url = 'http://www.academy.xyzq';
        if (1 === 1) {
          // Make this effect stop immediately and do nothing more
          return null;
        }
        action.url = url;
        return action;
      }),
      mergeMap((action: any) =>
        if(action){
        return this.http.get(action.url).pipe(
          switchMap((data: any) => {
            return [{
              type: 'INIT_ACADEMY',
              payload: {
                academy: data.academy
              }
            }];
          })
          } else{
            return null;
          }
        )),
      catchError(() => of ({
        type: 'INIT_IT_FAILED'
      }))
    );