【问题标题】:Angular combine and transform multiple http requests with forJoin Rxjs operatorAngular 使用 forJoin Rxjs 运算符组合和转换多个 http 请求
【发布时间】:2021-10-23 06:44:16
【问题描述】:

我正在将多个 http 请求与 forkJoin rxjs 运算符组合在一起。

fetchUsers() {
    const userIds = [1, 2, 3];
    const url = 'https://jsonplaceholder.typicode.com/users';

    forkJoin(userIds.map(id => this.http.get(`${url}/${id}`))).subscribe(
      console.log
    );
  }

所以,然后我订阅我得到三个对象,但我想改变这些对象并获得这样的结构

[{id:1, user: Object}, {id:2, user: Object}, {id:3, user:Object}];

我尝试过使用 of 运算符,但我得到了

[{id:1, user: Observable}] 

结构。 这是我的 stackblitz 链接https://stackblitz.com/edit/angular-ivy-uikppg?file=src%2Fapp%2Fapp.component.ts。谢谢

【问题讨论】:

    标签: angular rxjs operators fork-join


    【解决方案1】:

    您应该使用 rxjs map 运算符来转换数据,而不是在 forkJoin 中使用 of 运算符

        fetchUsers() {
            const userIds = [1, 2, 3];
            const url = 'https://jsonplaceholder.typicode.com/users';
        
            forkJoin(
              userIds.map(id => this.http.get(`${url}/${id}`).pipe((map(user=>({
                id,user
              })))))
            ).subscribe(console.log);
          }
    

    Forked Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2022-11-24
      • 2020-10-16
      • 1970-01-01
      相关资源
      最近更新 更多