Ngrx @Effects-立即停止

时间:2018-08-03 10:24:51

标签: angular ngrx ngrx-store ngrx-effects ngrx-store-4.0

我有以下ngrx效果。在“地图”中,我有一个条件。如何立即停止效果而又不继续执行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'
  }))
);

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您应该考虑使用filter函数根据您的情况过滤掉操作:

@Effect()
myEffect$: Observable < Action > = this.actions$.pipe(
  ofType('INIT_ACADEMY_DOMAIN'),
  filter((x) => 1 === 1),
  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'
  }))
);

或者,如果您的条件为true,则可以只调度一个新动作,并创建一个更简单的效果来执行mergeMap函数中的该部分。

您应该尝试使效果尽可能简单。如果您的效果要进行大量的逻辑/条件检查,那么很难找到一个合适的名称来捕获效果的实际作用。