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

时间:2018-10-02 13:49:32

标签: angular rxjs ngrx

在使用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)))
    )
  )
);

2 个答案:

答案 0 :(得分:4)

我想我有您(或未来的流浪者)想要的食谱。您必须将初始有效负载(下面的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))

答案 1 :(得分:1)

您应该能够使用箭头功能。

        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)))
              )
            )
          );