Wait two sequence actions before do something in ngrx effect angular

Viewed 773

I want to: create a book, then load list of books, then navigate to book detail page

Assume that I have 2 effects: load list book and create book. loadListBook effect work correctly (as before)

My create effect is written correct?

create$: Observable<Action> = this.action$.pipe(
  ofType<CreateBook>(BookActions.createBook),
  switchMap(action => {
    return this.bookService.create(action.payload).pipe(
      map(newbook => {
       console.log(newbook)
      }),
      catchError(error => of(  {
        type: 'CREATE_BOOK_FAILURE'
      }))
    );
  }),
  switchMap(bookInfo => [
    new LoadBookList()
  ]),
  tap(book => {
    // want to navigate to book detail here
    console.log(e);
  })
);
1 Answers

It looks correct. I would suggest separating this into smaller action specific effects instead of a big one so its more readable and you avoid queuing switchMaps

create$ = createEffect(() => this.actions$.pipe(
  ofType(BookActions.createBook)
  switchMap(action =>  
    return this.bookService.create(action.payload).pipe(
      map(() => BookActions.createBookSuccess(),
      catchError(err => of(BookActions.createBookFail({err}))
    );
  })
));

loadList$ = createEffect(() => this.actions$.pipe(
  ofType(BookActions.createBookSuccess)
  switchMap(() =>  
    return this.bookService.loadList().pipe(
      map(() => BookActions.loadListSuccess(),
      catchError(err => of(BookActions.loadListFail({err}))
    );
  })
));

redirect$ = createEffect(() => this.actions$.pipe(
  ofType(BookActions.loadListSuccess)
  tap(() => this.router.navigate(['book-detail-page']))
));
Related