Search code examples
angularswitchmap

switchmap and forjoin operator in angular


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)); 

Solution

  • 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