要访问ngrx效果下的状态,我们可以像这样使用withLatestFrom(取自文档https://ngrx.io/guide/effects):
this.actions$.pipe(
ofType(CollectionApiActions.addBookSuccess),
concatMap(action => of(action).pipe(
withLatestFrom(this.store.pipe(select(fromBooks.getCollectionBookIds)))
)),
tap(([action, bookCollection]) => {
if (bookCollection.length === 1) {
window.alert('Congrats on adding your first book!');
} else {
window.alert('You have added book number ' + bookCollection.length);
}
})
)
与我的应用程序中的许多效果一样,这种效果实际上不会访问我们使用withLatestFrom
获得的列表中的action
参数,而只对bookCollection
感兴趣。所以我想知道,为什么不简单地这样做:
function getLatestFrom<T, R>(observable: Observable<T>) {
return concatMap((action: R) => of(action).pipe(
withLatestFrom(observable),
map(([, value]) => value)
))
}
并将上面的代码段替换为
this.actions$.pipe(
ofType(CollectionApiActions.addBookSuccess),
getLatestFrom(this.store.pipe(select(fromBooks.getCollectionBookIds))),
tap(bookCollection => {
if (bookCollection.length === 1) {
window.alert('Congrats on adding your first book!');
} else {
window.alert('You have added book number ' + bookCollection.length);
}
})
)
这在我看来干净多了,但我在任何地方都没有发现这样的东西,所以我想知道是否有理由不这样做?
但只对bookCollection 感兴趣
与其使用从源和输入Observables返回结果数组的withLatestFrom
运算符,不如使用仅从输入observable返回结果的switchMapTo
,如下所示:
切换映射到
this.actions$.pipe(
ofType(CollectionApiActions.addBookSuccess),
switchMapTo(this.store.pipe(select(fromBooks.getCollectionBookIds), first())),
tap(bookCollection => {})
)
VS
WithLatestFrom
this.actions$.pipe(
ofType(CollectionApiActions.addBookSuccess),
withLatestFrom(this.store.pipe(select(fromBooks.getCollectionBookIds))),
tap(([action, bookCollection]) => {})
)