0

hi everyone I have a problem I try to explain it in the best possible way (I also created a stackblitz where I reproduce the code) I am using jsonplceholder. I make a first http get call to this url jsonplaceholder.typicode.com/users and I get an array of objects where each object is a user, for each user based on the id I would like to make a further call (probably I should use the switchMap because I can't make a subscribe inside another subscribe) to go and make an http get to this address for each user jsonplaceholder.typicode.com/todos/reste.id} after which for each user.id I get an object and ( I presume with a forkJoin) extrapolate title and insert it in each object of the result of the first call, of course each title for each user based on the id, here is the stackbliz, you can help me please I'm really bogged down I hope someone comes to my rescue https://stackblitz.com/edit/angular-ivy-n3pwc2?file=src/app/app.component.ts

this.http
.get<any>('https://jsonplaceholder.typicode.com/users')
// pipe switchmap map ????? 
.subscribe((res) => (this.users = res)); 
michelemalagnini
  • 149
  • 2
  • 10
  • I can only assume that you want to get users with todos. Ergo, your idea is invalid from the start since todo id does not correspond to user id. And since this mock api does not provide endpoint to get all todos for an user, your best bet is to call it once for all users and once for all todos and then join those lists by userId: https://stackblitz.com/edit/angular-ivy-7czhln?file=src/app/app.component.ts – Eggy Feb 01 '22 at 18:55

1 Answers1

1

You are basically right about using switchMap and forkJoin. One way to achieve it is as follows.

this.http
  .get<any>('https://jsonplaceholder.typicode.com/users')
  .pipe(
    switchMap((users) => {
      const sources$: Observable<any>[] = users.map((u) =>
        this.http
          .get(`https://jsonplaceholder.typicode.com/todos/${u.id}`)
          .pipe(
            map((todo: any) => ({
              id: u.id,
              name: u.name,
              title: todo.title,
            }))
          )
      );
      return forkJoin(sources$);
    })
  )
  .subscribe((res) => (this.users = res));


<!-- extend template -->
<ul>
  <li *ngFor="let u of users">
    {{ u.id }} - {{ u.name }} - "title" - {{ u.title }}
  </li>
</ul>

You can see it on Stackblitz here

Lukasz Gawrys
  • 1,234
  • 2
  • 8