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
相关产品推荐
相关产品推荐

