是否有类似于 withLatestFrom 但带有参数的 RxJS 运算符?

liv*_*mas 5 rxjs ngrx angular

我的 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}) => {
    ...
  })
)
Run Code Online (Sandbox Code Playgroud)

我知道这可能不是最好的解决方案,我正在寻找这样的东西(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]) => {
    ...
  })
)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:是否有任何类似于withLatestFrom可以将第一个流产生的值作为参数的RxJS 运算符?

Kri*_*obs 5

我终于做到了...

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
Run Code Online (Sandbox Code Playgroud)


car*_*ant 3

您可以使用mergeMapmap将该操作与从商店中选择的表结合起来:

@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]) => {
    ...
  })
)
Run Code Online (Sandbox Code Playgroud)

并且您需要使用first- 或take(1)- 来确保从存储中选择的内部可观察对象仅发出单个值 - 要与操作组合的表。