我要:创建一本书,然后加载书籍列表,然后导航至书籍详细信息页面
假设我有2种效果:加载清单书和创建书。 loadListBook效果正常工作(与以前一样)
我的创作效果写得正确吗?
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);
})
);
答案 0 :(得分:0)
然后在这种情况下,您应该使用mergeMap
从文档中
Maps each value to an Observable, then flattens all of these inner Observables using mergeAll.
示例
var letters = Rx.Observable.of('a', 'b', 'c');
var result = letters.mergeMap(x =>
Rx.Observable.interval(1000).map(i => x+i)
);
result.subscribe(x => console.log(x));
// Results in the following:
// a0
// b0
// c0
// a1
// b1
// c1
// continues to list a,b,c with respective ascending integers
答案 1 :(得分:0)
看起来是正确的。我建议将其分成较小的特定于动作的效果而不是较大的效果,这样它更具可读性,并且避免排队 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']))
));