I'm relatively new to Angular, and I'm still figuring things out. I've read/done the Tour of Heroes tutorial multiple times and read a lot of RxJS documentation and I'm still kind of stuck in this part of the code of a real project. I'm not new to JavaScript.
Typically, when I need to hydrate an object with external data I'd just use async/await to pull the data from the sources and manipulate it accordingly. I'm not sure if this is the accepted pattern using Angular.
I have multiple services that fetch data from different sources. Within the ngOnInit method of my component, I'm trying to call all those methods, but I'm not able to get the data directly without things getting too convoluted and I'm questioning whether this is the right way to do it within the Angular ecosystem.
This is a snippet of the code I'm writing, but it just feels wrong. What would be the idiomatic way to do it in Angular?
async fetchData(): Promise<void> {
const clients = await this.clientService.getClients();
clients.pipe(
map(c => c.map(client => this.jobService.getJobs(client.clientId))
).subscribe();
}
Essentially what I'm trying to do is:
- Fetch a list of clients from an API
- Iterate over the list of clients and request a list of jobs by clientId
- Wait until both requests are complete and push the data to a
BehaviorSubject - Have other components read data from that
BehaviorSubjectto render the data for the end-user