2

With the traditional observable/subscribe pattern I am trying to get a list of clients, with each of those clients get a list of their accounts with client.id

Here's what that looks like:

this.httpService.getClients().subscribe(clients => {
    clients.forEach(client => {
        this.httpService.getClientAccount(client.id).subscribe(accounts => {
            console.log(accounts);
        });
    });
});

Now I'm trying to do this with mergeMap. I do not think I'm doing it correctly as when I pass in client.id to the second call it is showing as undefined.

this.httpService.getClients().pipe(
    mergeMap(client => this.httpService.getClientAccount(client.id))
).subscribe(result => console.log(result))

Can anyone point out what I'm doing wrong here? I tried using tap() to console log the client inside mergeMap but nothing showed up. I'm not sure how to reference the response from the first getClients() call.

2 Answers2

0

Here is an example of how to use forkJoin as mentioned above by Chris W.:

const outerObservable = of([0, 1, 2, 3, 4]);

outerObservable.pipe(
    mergeMap(inputs => forkJoin(inputs.map(input => rxjs.of(input)))),
);

outerObservable.subscribe(console.log);

See example 3 from this page and example 1 for info on how to use a dictionary approach.

Tim Klein
  • 2,538
  • 15
  • 19
0

I'm not sure if this is correct way to do it but this returns each account for each client:

this.clientService.getAllClients().pipe(
    mergeMap(clients => clients)).pipe(
    mergeMap((client:any) => this.accountService.getClientAccts(client.id)))
    .subscribe(res=>console.log(res));

The first mergeMap flattens the clients array to each individual client I believe then can use client.id to make the second call.