如何从角度6的http请求中仅获取特定字段

时间:2019-07-14 07:35:38

标签: angular

我只想从服务发出的http请求中提取选择性字段。例如名称,其余网址resturl link

中的货币

服务

 public fetchRecords(name): any {
    const searchParam = 'united';
    const urlPath = 'https://restcountries.eu/rest/v2/name/' + searchParam;
    return this.http.get(urlPath).pipe(map(
      res => res
      ));
  }

组件

getCountries() {
this.service.fetchRecords(this.searchWord).subscribe(res => {
  this.result = res;
});

2 个答案:

答案 0 :(得分:3)

尝试使用RXJS地图运营商

getCountries() {
this.service.fetchRecords(this.searchWord)
.pipe(
  map(data => data.map(({name, currencies })=>({name, currencies })))
)
.subscribe(res => {
  this.result = res;
});

Working Demo

答案 1 :(得分:1)

不行,HttpClient仅帮助您发送请求。 REST服务器端代码中定义了返回的内容。但是您可以map将结果返回到多种货币[]中:

public fetchCurrency(name): any {
    const searchParam = 'united';
    const urlPath = 'https://restcountries.eu/rest/v2/name/' + searchParam;
    return this.http.get(urlPath).pipe(map(
      res => res.map(({name, currencies })=>({name, currencies})) 
    ));
}