Search code examples
angularreduxrxjsngrx

having an effect dispatch different action in different case


I have the following effect

  @Effect()
  assignMission$ = this.actions$.pipe(
    ofType<featureActions.AssignUAVMissionRequest>(featureActions.ActionTypes.AssignUAVMissionRequest),
    concatMap(action =>
      of(action).pipe(
        withLatestFrom(this.store$.pipe(select(RoutesStoreSelectors.getById(), {routeId: action.payload.routeId}))),
      )
    ),
    switchMap(([action, route]) => {
      return this.dataService.assignUAVMission(action.payload.params).pipe(
        mergeMap(response => {
          if (route.saveState === RoutesStoreModels.IRouteSaveState.DRAWED) {
            return [
              new RoutesStoreActions.OverrideRoute(),
              new featureActions.AssignUAVMissionSuccess()
            ];
          } else {
            const newRouteId = uuid();
            return [
              new RoutesStoreActions.AddRoute(),
              new featureActions.AssignUAVMissionSuccess()
            ];
          }
        }),
        catchError((error: HttpErrorResponse) => {
          return of(new featureActions.AssignUAVMissionFailed({error}));
        }),
      );
    })
  );

in one case, I want to dispatch OverrideRoute and AssignUAVMissionSuccess in another case I want to dispatch AddRoute and AssignUAVMissionSuccess instead.

the problem is, my mergeMap return an error

ERROR in src/app/stores/uavs-store/effects.ts(218,18): error TS2345: Argument of type '(response: AssignMissionResponse) => (AssignUAVMissionSuccess | OverrideRoute)[] | (AssignUAVMissionSuccess | AddRoute)[]' is not assignable to parameter of type '(value: AssignMissionResponse, index: number) => ObservableInput'.

But I don't exactly see how is this fixable ?

Is it possible to have an effect dispatch different set of action ?


Solution

  • You can solve it by returning an array of type Action like this -

    mergeMap(response => {
    
              const actions = new Array<Action>();
              if (route.saveState === RoutesStoreModels.IRouteSaveState.DRAWED) {
              actions.push(new RoutesStoreActions.OverrideRoute());
               actions.push(
                  new featureActions.AssignUAVMissionSuccess()
                );
               return actions;
              } else {
                const newRouteId = uuid();
               actions.push(new RoutesStoreActions.AddRoute());
               actions.push(
                  new featureActions.AssignUAVMissionSuccess()
                );
                return actions;
              }
            })