I have 3 selectors:
getUserInfo
=> to fetch acnt details (sample output : {acntId: 'A1'}
)getAllDepartments
=> to fetch list of all dept Ids (sample Output: ['d1','d2']
)getAllDeptManagers
=> to get list of dept managers for each Dept Id.Now, I have written below code:
this.store
.select(getUserInfo)
.pipe(
switchMap((res) => this.store.select(getAllDepartments, { account: res.acntId})),
mergeMap(deptId => this.store.select(getDepartmentManagers,{departmentId: deptId }))
)
.subscribe((depts) => {
console.log(depts);
})
);
As per my understanding, mergeMap
takes array and accordingly call a function
and flatten the array of observable which is returned.
I am getting ['d1','d2']
in every call to selector getAllDeptManagers
. what I am expecting is d1
and then d2
and so on, and then get all response in one go as depts
of console.
Please help
mergeMap
doesn't flatten the output from its inner Observable. It just reemits when the inner Observable emits and that's it. So it looks like you want to use forkJoin
here:
mergeMap(deptIds => forkJoin(
deptIds.map(deptId => this.store.select(getDepartmentManagers, {
departmentId: deptId
}).pipe(take(1)))
)),
Then observers will receive a single array of results for deptIds
because forkJoin
will wait until all of the inner Observavbles complete.