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

Angular 10 HttpClient Get请求返回Undefined问题求助

Angular 10 HttpClient请求返回Undefined问题解决

问题根源

你调用的API返回的data是数组类型(即便里面只有一个元素),但你直接通过response.data.name、response.data.weather的方式访问属性——数组本身没有这些对象属性,所以会返回undefined。

看API原始响应:

{"page":1,"per_page":10,"total":1,"total_pages":1,"data":[{"name":"Dallas","weather":"12 degree","status":["Wind: 2Kmph","Humidity: 5%"]}]}

这里data的值是[ {...} ],是数组而非单个对象。

修正代码

先从data数组中取出第一个元素,再访问对应属性;另外status也是数组,需要解析字符串提取风速和湿度:

@Component({ 
  selector: 'weather-finder', 
  templateUrl: './weatherFinder.component.html', 
  styleUrls: ['./weatherFinder.component.scss'] 
}) 
export class WeatherFinder implements OnInit { 
  constructor(private http: HttpClient) { } 

  search: string; 
  name: any = null; 
  weather: any; 
  wind: any; 
  humidity: any; 
  abc: string; 

  fetch() { 
    const url = `https://jsonmock.hackerrank.com/api/weather?name=${this.search}`;
    return this.http.get<any>(url); 
  } 

  onFetch(abc: string) { 
    this.search = abc; 
    this.fetch().subscribe((response: any) => {
      console.log(response);
      // 取出data数组里的第一个对象
      const weatherItem = response.data[0];
      if (weatherItem) {
        this.name = weatherItem.name;
        this.weather = weatherItem.weather;
        console.log(this.weather); // 现在会输出"12 degree"
        
        // 解析status数组中的风速和湿度
        weatherItem.status.forEach(item => {
          if (item.startsWith('Wind:')) {
            this.wind = item.split(':')[1].trim();
          } else if (item.startsWith('Humidity:')) {
            this.humidity = item.split(':')[1].trim();
          }
        });
      }
    })
  }
}

额外建议

  • 避免使用var,改用const或let,符合TypeScript最佳实践
  • 可以给API响应定义接口类型,避免any类型带来的类型不安全问题,示例:
    interface WeatherResponse {
      page: number;
      per_page: number;
      total: number;
      total_pages: number;
      data: WeatherItem[];
    }
    
    interface WeatherItem {
      name: string;
      weather: string;
      status: string[];
    }
    
    之后请求时用this.http.get<WeatherResponse>(url),能获得更友好的类型提示。

内容的提问来源于stack exchange,提问作者Ankit_jackar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:04:45