【问题标题】:How to extract only certain fields from Http response object如何从 Http 响应对象中仅提取某些字段
【发布时间】:2021-10-13 17:37:24
【问题描述】:

我对 Angular 还很陌生,我试图从 Http 响应对象中只获取某些值。

在我的服务中,我正在执行获取请求以获取给定城市的天气数据,如下所示:

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}`);
  }
}

现在,在组件中,我正在注销响应,如下所示:

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

响应本身只是一个包含许多字段(也是嵌套字段)的对象,其中大多数我不需要。

我还设置了一个界面,我想在这些特定响应字段中“保存”:

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

我该怎么做?干杯!

编辑: 根据下面的答案,我得到了 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
    }));

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    一种解决方案可能是在您的服务中映射对象。然后您的服务将返回 City 对象。

    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.
      }
    }
    

    如果您不希望您的服务始终返回 City 对象,您可以在您的组件中进行此映射。

    【讨论】:

    • 我现在遇到 2 个错误:1. 类型 'Observable' 不能分配给类型 'Observable'。类型“void”不可分配给类型“City”。 2.“对象”类型上不存在属性“名称”。
    • 进行了编辑。在 stackoverflow 文本编辑器中编码。我的错误。有一些语法错误。您应该在地图中返回。
    • 不用担心。我还找到了解决方法,并编辑了我的帖子。再次干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    相关资源
    最近更新 更多