Search code examples
angularngrxngrx-effects

Access the a action payload after switchmap(api call) in ngrx Effect


 saveQuiz$ = createEffect(() =>
    this.actions$.pipe(
      ofType(quizActions.addQuiz),
      map(action => action.saveQuiz),
      switchMap((quiz) => this.quizDataService.postQuiz(quiz)),
      tap((quizId) => console.log('NEED THE ACTION PAYLOAD HERE')),
      map((quizId:number) => quizActions.addQuizSuccess({quiz:{ id:quizId }})),
      catchError(() => EMPTY)
    )
  );

This the effect that i created , the issue is i need to access the action.payload after the switchmap (which calls the api). Is there any way i can do it ?


Solution

  • You can do something like this:

    import { combineLatest, of } from 'rxjs';
    .....
    saveQuiz$ = createEffect(() =>
        this.actions$.pipe(
          ofType(quizActions.addQuiz),
          map(action => action.saveQuiz),
          switchMap((quiz) => { return combineLatest(of(quiz), this.quizDataService.postQuiz(quiz)); }),
          tap(([quizAction, quizId]) => console.log(`${quizAction}, ${quizId}`)),
          map(([, quizId]) => quizActions.addQuizSuccess({quiz:{ id:quizId }})),
          catchError(() => EMPTY)
        )
      );