Home > Net >  Using switchMap to dispatch an action fails while map works
Using switchMap to dispatch an action fails while map works

Time:10-09

I just started using ngrx and ngrx/effects.

In the following code using switchMap to get the results from concatLatestFrom and dispatching an action fails while using map works. Why is that??

Using switchMap doesn't compile at all and when i hover on it, it shows

Argument of type '([action, staff]: [{ per_page: number; } & TypedAction<"[Admin] Fetch All Staff From Store">, Staff[]]) => ({ per_page: number; } & TypedAction<"[Admin] Get All Staff Start">) | { ...; }' is not assignable to parameter of type '(value: [{ per_page: number; } & TypedAction<"[Admin] Fetch All Staff From Store">, Staff[]], index: number) => ObservableInput'. Type '({ per_page: number; } & TypedAction<"[Admin] Get All Staff Start">) | { type: string; }' is not assignable to type 'ObservableInput'. Type '{ per_page: number; } & TypedAction<"[Admin] Get All Staff Start">' is not assignable to type 'ObservableInput'. Property '[Symbol.iterator]' is missing in type '{ per_page: number; } & TypedAction<"[Admin] Get All Staff Start">' but required in type 'Iterable'.ts(2345)

which i dont understand.

This Gives an error.

GetAllStaffFromStore = createEffect(() =>
    this.action$.pipe(
      ofType(adminActions.FetchAllStaffFromStore),
      concatLatestFrom((action) =>
        this.store.select(fromAdminReducer.selectStaff)
      ),
      switchMap(([action, staff]) => {
        if (staff.length === 0) {
          return adminActions.GetAllStaffStart({ per_page: action.per_page });
        } else {
          return {
            type: "Getting Staff From Store",
          };
        }
      })
    )
  );

This works

GetAllStaffFromStore = createEffect(() =>
    this.action$.pipe(
      ofType(adminActions.FetchAllStaffFromStore),
      concatLatestFrom((action) =>
        this.store.select(fromAdminReducer.selectStaff)
      ),
      map(([action, staff]) => {
        if (staff.length === 0) {
          return adminActions.GetAllStaffStart({ per_page: action.per_page });
        } else {
          return {
            type: "Getting Staff From Store",
          };
        }
      })
    )
  );

CodePudding user response:

switchMap has to return a new Observable

Wrapping the response in of operator should help.

import { of } from 'rxjs';

GetAllStaffFromStore = createEffect(() =>
    this.action$.pipe(
      ofType(adminActions.FetchAllStaffFromStore),
      concatLatestFrom((action) =>
        this.store.select(fromAdminReducer.selectStaff)
      ),
      switchMap(([action, staff]) => {
        if (staff.length === 0) {
          return of(adminActions.GetAllStaffStart({ per_page: action.per_page }));
        } else {
          return of({
            type: "Getting Staff From Store",
          });
        }
      })
    )
  );
  • Related