【问题标题】:mapping from rest response从休息响应映射
【发布时间】:2020-05-05 05:46:47
【问题描述】:

我正在使用 Dog Api (https://dog.ceo/api/breeds/list/all) 进行示例,品种端点的响应是这样的:

{
    "message": {
           "affenpinscher": [],
           "african": [],
           "airedale": [],
           "akita": [],
           "appenzeller": [],
           "australian": ["shepherd"]
}

我需要我的品种服务,返回一个可观察的品种

export class Breed {
    name : String;  
    subbreeds : String[]
}

此调用返回一个具有属性message 的对象。我如何在我的服务中映射以从该 API Rest 响应返回 Observable<Breed[]>

getAll() : Observable<Breed[]> {  
    return this.http.get<Breed[]>("https://dog.ceo/api/breeds/list/all");   
}

【问题讨论】:

  • 分享您用来拨打电话的代码。它应该返回Breed 还是Breed[]

标签: arrays rxjs angular8


【解决方案1】:

其实这个问题与 rxjs 和 Angular 8 无关,而是关于 JavaScript。

export class Breed {
  // public modifier is a short hand for this.name = name
  constructor(public name: string, public subbreeds: string[]) {}
}

class Service {
  getAll() {
    return this.http
      .get<Breed[]>('https://dog.ceo/api/breeds/list/all')
      .pipe(
        map(data => // map here is a rxjs operator, do not confuse with JS array's map
          // Object.entries is convert Object's key value to entries [key, value] array
          Object.entries(data.message).map( // JS array map method mapping each entry to Breed instance
            // destructing from entry and return a Breed instance
            ([breed, subbreed]) => new Breed(breed, subbreed)
          ),
        ),
      );
  }
}

如果你不确定任何术语或方法,请查看 MDN 和 RxJS 官方文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    相关资源
    最近更新 更多