NGRX Effects how to pass parameter to withLatestFrom operator

大兔子大兔子 提交于 2019-12-08 08:26:27

问题


I am struggling with passing parameter to selector when by using withLatestFrom, which was mapped earlier from load action payload

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

回答1:


I think I have the recipe you (or future wanderers) are looking for. You have to map the initial payload (of operator below) to an inner observable so that it can be piped and passed as a param to withLatestFrom. Then mergeMap will flatten it and you can return it to the next operator as one array with the initial payload as the first value.

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



回答2:


You should be able to use an arrow function.

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


来源:https://stackoverflow.com/questions/52609748/ngrx-effects-how-to-pass-parameter-to-withlatestfrom-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!