You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何从Observable提取OpenWeatherMap接口的指定字段?

问题核心原因

OpenWeatherMap 接口返回的完整数据中,temp、feels_like、temp_min、temp_max 四个字段统一嵌套在返回根对象的 main 属性下,你之前直接将完整返回结果强转为 LocationData 类型,自然无法直接取到对应字段。

解决步骤

1. 调整天气服务代码

首先在服务中引入RxJS的map操作符,接口请求后通过map提取嵌套在main下的目标字段,直接映射为LocationData类型返回即可:

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import {LocationData} from "../models/location-data";

@Injectable({
  providedIn: 'root'
})
export class WeatherServiceService {

  constructor(public http: HttpClient) {
  }

  getData() : Observable<LocationData>{
    // 原始返回结构不是LocationData,泛型先用any
    return this.http.get<any>('https://api.openweathermap.org/data/2.5/weather?q=Enschede&appid=2a47a80c223baab80003883c31f35729')
    .pipe(
      map(res => {
        // 提取main下的对应字段组装为LocationData
        return {
          temp: res.main.temp,
          feels_like: res.main.feels_like,
          temp_min: res.main.temp_min,
          temp_max: res.main.temp_max
        } as LocationData
      })
    )
  }
}

注:建议将接口请求协议从http改为https,避免浏览器混合内容限制导致请求失败。

2. 组件逻辑无需修改

你现有的getCoordinates方法可以直接使用,服务返回的已经是处理好的LocationData类型数据,订阅后直接赋值就能正常读取四个字段:

getCoordinates(){
  this.weatherService.getData().subscribe((data: LocationData) => {
    this.locationData = data
    // 此处可直接使用字段,比如 console.log(this.locationData.temp)
  })
}

你现有的LocationData模型完全不需要调整,后续如果需要新增其他字段,只要在模型中加对应属性,同时在服务的map返回中新增字段映射即可。

内容的提问来源于stack exchange,提问作者Koen ter Heegde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:45:04