将 WithLatestFrom 的值传递给另一个运算符 - Rxjs,Ngrx 效果

Pass the value from WithLatestFrom to another operator - Rxjs, Ngrx effect

我得到了这个 ngrx 效果,我想使用来自我的状态的数据 withLatestFrom

$loadProduct = createEffect(() =>
  this.actions$.pipe(
    ofType(fromActions.loadProduct),
    withLatestFrom(this.store.select(fromSelectors.debounceTime)),
    delay(debounceTime), // how can I get the debounceTime value up here?
    map(_ => fromActions.foo())
  )
)

如何在延迟范围内得到这个debounceTime值?

这个怎么样:

$loadProduct = createEffect(() =>
  this.actions$.pipe(
    ofType(fromActions.loadProduct),
    withLatestFrom(this.store.select(fromSelectors.debounceTime)),
    switchMap(([_, debounceTime]) => timer(debounceTime)),
    map(_ => fromActions.foo())
  )
)

它使用 RxJS 的 switchMap and timer 而不是延迟。

顺便说一句,如果你不需要在管道后续部分的某个地方执行操作,你也可以使用 switchMap 而不是 withLatestFrom ,如下所示:

$loadProduct = createEffect(() =>
  this.actions$.pipe(
    ofType(fromActions.loadProduct),
    switchMap(() => this.store.select(fromSelectors.debounceTime)),
    switchMap(debounceTime => timer(debounceTime)),
    map(() => fromActions.foo())
  )
)

既然delay就是delayWhen(() => timer(duration));,我想你可以用delayWhen来解决问题:

$loadProduct = createEffect(() =>
  this.actions$.pipe(
    ofType(fromActions.loadProduct),
    withLatestFrom(this.store.select(fromSelectors.debounceTime)),
    
    delayWhen(([, debounceTimeVal]) => timer(debounceTimeVal)),

    map(_ => fromActions.foo())
  )
)

附带说明一下,delayWhen 只是 an interesting use case of mergeMap:不是发出内部值,而是发出外部值。