How can I use correctly chain together 3 types of http requests, where each request relies on data from the previous, and there might be a dynamic amount of needed requests depending on what was returned?
In my database I have a team table, where a team has a businessId that it belongs to. I have a supervisor table, which has a teamId that it belongs to. And I have an employee table, which have supervisorId that they report to.
I hope this makes sense so far.
I'm still learning RxJS, so forgive me if my interpretation for these operators is wrong, but I'm going to try and describe the workflow.
- Depending on the business selected, we get all the teams associated with that business and save them
- Now there could be 4 teams, so we iterate through each team and store the observable in an array
- Then we return forkJoin on the array of observables so that it waits until they are all done
- Now concatMap again, because we won't know which employees to get without the supervisors data
- doing the same process, we might have 3 supervisor id's, so create an array of observables for all the supervisors
- Do the forkJoin again, returning observables for the employees
- finally, subscribe to the last forkJoin to get the employee data.
Here's my current code:
onSelectBusiness(event): void {
this.selectedBusinessId = event.target.value;
this._service.getAllTeams(this.selectedBusinessId).pipe(
concatMap((_teams) => {
let supervisorObservables: any[] = [];
_teams.forEach(t => {
// Need to call this http request for however many different teams there are
this.teams.push(t); // Saving the teams
supervisorsObservables.push(this._service.getAllSupervisors(t.teamId))
})
return forkJoin({supervisorObservables}).pipe(
concatMap((_supervisors) => {
let employeeObservables: any[] = [];
employeeObservables.forEach(s => {
this.supervisors.push(s); // saving supervisors
// Need to call this http request for as many different supervisors there are
employeeObservables.push(this._service.getAllEmployees(s.supervisorId))
})
return forkJoin({employeeObservables})
})
)
})
).subscribe(
({employeeObservables}) => {
// Even console.logs are not displaying
employeeObservables.forEach(e => {
this.employees.push(e); // Supposed to get my employee data here, but im not
})
}
)
}
The main problem is that in the final subscribe, nothing happens in there. I'm able to get teams and supervisors data, but not employees.
I've tried to add another:
// Same as above code
// ...
return forkJoin({employeeObservables}).pipe(
concatMap(_employees) => {
// but I have no other http request to return, which is required by concatMap
// and I can't simply subscribe to this forkJoin because concatMap requires the subscribe at the bottom
}
)
I'm not even sure if its possible to do what I want, regarding the forEach loops and forkJoins inside of the concatMaps..
Any and all comments/help/tips is greatly appreciated! :)