angular 中的 switchmap 和 forkjoin 运算符

switchmap and forjoin operator in angular

大家好,我有一个问题,我尝试以最好的方式解释它(我还创建了一个 stackblitz,在其中重现代码)我正在使用 jsonplceholder。我对这个 url jsonplaceholder.typicode.com/users 进行了第一个 http get 调用,我得到了一个 objects 数组,其中每个 object 都是一个用户,对于每个基于 id 的用户我想进一步调用(可能我应该使用 switchMap,因为我不能在另一个订阅中进行订阅)去为每个用户做一个 http 访问这个地址 jsonplaceholder.typicode .com/todos/reste.id} 之后,对于每个 user.id 我得到一个 object 并且(我假设使用 forkJoin)推断标题并将其插入结果的每个 object 中第一次调用,当然每个用户的每个标题都基于 id,这里是 stackbliz,你可以帮助我我真的陷入困境我希望有人来拯救我 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)); 

您使用 switchMapforkJoin 基本上是正确的。实现它的一种方法如下。

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