Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGRX Effects how to pass parameter to withLatestFrom operator

Tags:

angular

rxjs

ngrx

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)))
    )
  )
);
like image 936
Jake11 Avatar asked Oct 02 '18 13:10

Jake11


1 Answers

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))
like image 116
Preda70R Avatar answered Sep 19 '22 00:09

Preda70R