Search code examples
angularreduxngrxngrx-effects

Use WithlatestFrom with multiple observables that have dependency on each other


I'm trying to creating effect for angular using NgRx 12. I need to use data from multiple selectors, but one selector (isLoading)'s parameters comes from the first selector. Is it possible to get the data from here?

      withLatestFrom(
        this.store.pipe(select(fromA.getFormData)), // need to get data from here
        this.store.pipe(select(fromA.getFiles)),
        this.store.pipe(select(fromB.isLoading(formData.someValue // to here)),
        (action: Action, formData: any, files: Array<Attachment>) => ({ formData, files, isLoading })
      ),
      mergeMap(({ formData, files, isLoading }) => {
      ...

Thanks before!


Solution

  • Probably there is a better way, you could do it like this if you also want the form data to be used in mergeMap

    withLatestFrom(
     this.store.pipe(select(fromA.getFormData)).pipe(
      switchMap((theFormData) => this.store.select(fromB.isLoading(theFormData)))
     ),
     this.store.select(fromA.getFiles),
     this.store.pipe(select(fromA.getFormData))
    ),
    mergeMap([theLoadingValue, theFiles, theFormValue] => {...})
    

    If you don't care about the form data then it would simply be:

    withLatestFrom(
     this.store.pipe(select(fromA.getFormData)).pipe(
      switchMap((theFormData) => this.store.select(fromB.isLoading(theFormData)))
     ),
     this.store.select(fromA.getFiles)
    ),
    mergeMap([theLoadingValue, theFiles] => {...})