简体   繁体   English

如何仅从 Http 响应对象中提取某些字段

[英]How to extract only certain fields from Http response object

I'm fairly new to Angular and I'm trying to get only certain values from the Http response object.我对 Angular 还很陌生,我试图只从 Http 响应对象中获取某些值。

In my service, I'm doing a get request to fetch weather data for a given city like so:在我的服务中,我正在执行 get 请求以获取给定城市的天气数据,如下所示:

export class CityService {
  private baseUrl = 'https://api.openweathermap.org';

  constructor(private http: HttpClient) { }

  getCity(name: string){
    return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`);
  }
}

Now, in the component, I'm logging out the response like so:现在,在组件中,我像这样注销响应:

ngOnInit(): void {
    this.cityService.getCity('lucija').subscribe(data => {
      console.log(data)
    });
  }

The response itself it's just one object with many fields (also nested ones), which most of them I do not need.响应本身只是一个具有许多字段(也是嵌套字段)的对象,其中大多数我不需要。

I've also set up an interface where I would like to "save" in those certain response fields:我还设置了一个界面,我想在这些特定的响应字段中“保存”:

export interface City {
  name: string;
  description: string;
  icon: string;
  main: object;
  search: string;
}

How can I do that?我怎样才能做到这一点? Cheers!干杯!

EDIT: Based on the answer below I got 2 errors, which I resolved like so:编辑:根据下面的答案,我遇到了 2 个错误,我是这样解决的:

getCity(name: string): Observable<City>{
    return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`)
    .pipe(map((res: any) => <City>{
      name: res.name,
      description: res.weather[0].description,
      icon: `http://openweathermap.org/img/w/${res.weather[0].icon}.png`,
      main: res.main,
      search: name
    }));

One solution could be to map the object in your service.一种解决方案可能是映射服务中的对象。 Then your service will return the City Object.然后您的服务将返回城市对象。

export class CityService {
  private baseUrl = 'https://api.openweathermap.org';

  constructor(private http: HttpClient) { }

  getCity(name: string): Observable<City>{
    return this.http.get(`${this.baseUrl}/data/2.5/weather?q=${name}&appid=${environment.weatherApiKey}`)
     .pipe(map((res) => { return { name: res.cityName }; }); // only added name as example. In the final code map all the values to the correct City field.
  }
}

If you do not want your service to always return the City object you can do this mapping in your component.如果您不希望您的服务始终返回 City 对象,您可以在您的组件中进行此映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM