我的Angular 5应用程序基于NgRx,这是一个类似于Redux但基于RxJS的状态管理库。
我经常需要根据当前操作的有效负载从存储中获取最新的值。
在RxJS术语中,这意味着我有不断产生项目的主流,对于每个新项目,我需要基于项目的值创建一个副流,从该流中获取最新的值,并将其与主流组合。
目前,我这样做:
@Effect()
public moveCursor$: Observable<Action> = this.actions$.pipe(
ofType<TableAction.MoveCursor>(TableActionType.MOVE_CURSOR),
switchMap(action => this.store$.select(selectTableById(action.payload.cursor.tableId)).pipe(
first(),
map(table => ({action, table}))
)),
map(({action, table}) => {
...
})
)我知道这可能不是最好的解决方案,我正在寻找类似这样的东西(对于withLatestFrom运算符,这是不可能的):
@Effect()
public moveCursor$: Observable<Action> = this.actions$.pipe(
ofType<TableAction.MoveCursor>(TableActionType.MOVE_CURSOR),
withLatestFrom(action => this.store$.select(selectTableById(action.payload.cursor.tableId))),
map(([action, table]) => {
...
})
)所以我的问题是:有没有类似于withLatestFrom的RxJS运算符,可以将第一个流产生的值作为参数?
发布于 2019-02-28 23:11:48
我终于做到了..。
doEffect$ = this.actions$.pipe(
ofType<someAction>(losActionTypes.someAction),
switchMap/mergeMap/concatMap( // according to your logic
action => of(action).pipe(
withLatestFrom(this.store.pipe(select(leFancySelector)))
)),
tap(console.log) // tap if you don't believe me发布于 2018-03-12 06:49:50
您可以使用mergeMap和map将操作与从存储中选择的表组合在一起:
@Effect()
public moveCursor$: Observable<Action> = this.actions$.pipe(
ofType<TableAction.MoveCursor>(TableActionType.MOVE_CURSOR),
mergeMap(action => this.store$
.select(selectTableById(action.payload.cursor.tableId))
.pipe(
first(),
map(table => [action, table])
)
),
map(([action, table]) => {
...
})
)发布于 2021-10-27 23:54:22
我可能来晚了你已经解决了,但是...
首先,我不能清楚地看到你在这里想要实现什么。你有意的行为是什么?
仅当您的TableActionType.MOVE_CURSOR被调用并且具有来自您的存储的最新值时
或
调用TableActionType.MOVE_CURSOR或更新商店中的最新值时
如果只在调用TableActionType.MOVE_CURSOR时使用存储中的最新值,那么只使用withLatestFrom就足够了
@Effect()
public moveCursor$: Observable<Action> = this.actions$.pipe(
ofType<TableAction.MoveCursor>(TableActionType.MOVE_CURSOR),
withLatestFrom(this.store$.select(selectTableById(action.payload.cursor.tableId))),
map(([action, table]) => {
...
})
)如果它是*,那么当调用您的TableActionType.MOVE_CURSOR或更新商店中的最新值时,我将使用mergeMap来组合您的可观察操作和您从商店中获得的最新值
//Actions Observable
this.actions$.pipe(ofType<TableAction.MoveCursor>(TableActionType.MOVE_CURSOR))
//Latest Value from the store
this.store$.select(selectTableById(action.payload.cursor.tableId))
//Result:
@Effect()
public moveCursor$: Observable<Action> = mergeMap([
this.actions$.pipe(ofType<TableAction.MoveCursor>(TableActionType.MOVE_CURSOR)),
this.store$.select(selectTableById(action.payload.cursor.tableId))
]).map(({action, table}) => {
...
});但要注意,这将导致每次更新选择器时都会运行效果。(假设您的tableId是一个memoized,这应该是可以的。
https://stackoverflow.com/questions/49225314
复制相似问题