NGRX影响如何将参数传递给withLatestFrom运算符

Jak*_*e11 1 rxjs ngrx angular

使用withLatestFrom时,我正在努力将参数传递给选择器,这是从加载动作有效负载中较早映射的

loadLocalSubServices$: Observable<Action> = this.actions$.pipe(
  ofType(LocalSubServiceTemplateActions.LocalSubServicesTemplateActionTypes.LoadLocalSubService),
  map((action: LocalSubServiceTemplateActions.LoadLocalSubService) => action.payload.globalSubServiceId),
  // and below I would like to pass globalSubServiceId
  withLatestFrom(this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId)))),
  map(searchParams => searchParams[1]),
  mergeMap((params) =>
    this.subServiceService.getLocalSubServices(params).pipe(
      map(localSubServices => (new LocalSubServiceTemplateActions.LocalSubServiceLoadSuccess(localSubServices))),
      catchError(err => of(new LocalSubServiceTemplateActions.LocalSubServiceLoadFail(err)))
    )
  )
);
Run Code Online (Sandbox Code Playgroud)

Pre*_*70R 12

我想我有您(或未来的流浪者)想要的食谱。您必须将初始有效负载(of下面的运算符)映射到一个内部可观察对象,以便可以通过管道将其作为参数传递给withLatestFrom。然后mergeMap将其展平,您可以将其作为一个数组返回给下一个运算符,并以初始有效载荷作为第一个值。

map(action => action.payload),
mergeMap((id) =>
    of(id).pipe(
        withLatestFrom(
            this.store.pipe(select(state => getEntityById(state, id))),
            this.store.pipe(select(state => getWhateverElse(state)))
        )
    ),
    (id, latestStoreData) => latestStoreData
),
switchMap(([id, entity, whateverElse]) => callService(entity))
Run Code Online (Sandbox Code Playgroud)


Jua*_*ina 5

您应该能够使用箭头函数。

loadLocalSubServices$: Observable<Action> = this.actions$.pipe(
    ofType(LocalSubServiceTemplateActions.LocalSubServicesTemplateActionTypes.LoadLocalSubService),
    map((action: LocalSubServiceTemplateActions.LoadLocalSubService) => action.payload.globalSubServiceId),
    (globalSubServiceId) => {
        return withLatestFrom(this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId))));
    },
    map(searchParams => searchParams[1]),
    mergeMap((params) =>
      this.subServiceService.getLocalSubServices(params).pipe(
        map(localSubServices => (new LocalSubServiceTemplateActions.LocalSubServiceLoadSuccess(localSubServices))),
        catchError(err => of(new LocalSubServiceTemplateActions.LocalSubServiceLoadFail(err)))
      )
    )
  );     
Run Code Online (Sandbox Code Playgroud)


wlf*_*wlf 5

您现在可以使用concatLatestFrom来处理这个问题。

代替:

withLatestFrom(this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId)))),
Run Code Online (Sandbox Code Playgroud)

和:

concatLatestFrom(globalSubServiceId =>
 this.store.pipe(select(fromLocalSubservices.getSearchParams(globalSubServiceId)))
Run Code Online (Sandbox Code Playgroud)

https://v11.ngrx.io/api/effects/concatLatestFrom