【问题标题】:Mapping Key Value Pair from request using RxJS and observable使用 RxJS 和 observable 从请求映射键值对
【发布时间】:2021-10-07 14:51:26
【问题描述】:

我的 API 端点返回 json 作为键值对结果。如何将此集合映射到 .pipe 方法中的对象 ICar 。我需要 observable,因为我想缓存结果。

示例 json 结果:

{"1":"Ford", "2":"Toyota"}

我的示例代码:

export interface ICar {
  key: string;
  carName: string;
}

getCars():Observable<ICar[]> {
   return this.httpClient.get("https://cars.com/cars")
      .pipe(
          map(???),   <--------------dont't know how to map it here
          publishReplay(1), 
          refCount()
      );
}

【问题讨论】:

    标签: angular rxjs observable


    【解决方案1】:

    您有多种选择:

    map(response => {
      const result = [];
      for(const key in response) {
        result.push({key, carName: response[key]});
      }
      return result;
    }),
    
      map(response => Object.key(response).map(key => ({key, carName: response[key] }))});
    

    【讨论】:

      【解决方案2】:

      您好,它的对象不是数组,因此您需要手动循环

          for (const property in object) {
        console.log(`${property}: ${object[property]}`);
      }
      

      你需要这样做

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多