Angular调用世界银行API时数据返回undefined问题求助
从世界银行API提取数据时所有字段返回
undefined的问题 我的Angular服务代码:
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { AnyArray } from 'mongoose'; import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) { } fetchCountryData (country: string) { let formattedCountry = country.split('-').join(' '); let api1 = `http://api.worldbank.org/v2/country/${formattedCountry}?format=json`; let api2 = `` return this.http.get(api1) } setCountryData(country: string) { let subject = new Subject(); this.fetchCountryData(country).subscribe((data: any) => { subject.next({ country: data.name, capital: data.capitalCity, income: data.incomeLevel, region: data.adminregion, latitude: data.latitude, longitude: data.longitude, }) }) return subject.asObservable(); } }
API响应结构:
(2) [{…}, Array(1)] 0 : {page: 1, pages: 1, per_page: '50', total: 1} 1 : Array(1) 0 : adminregion : {id: 'EAP', iso2code: '4E', value: 'East Asia & Pacific (excluding high income)'} capitalCity : "Beijing" id : "CHN" incomeLevel : {id: 'UMC', iso2code: 'XT', value: 'Upper middle income'} iso2Code : "CN" latitude : "40.0495" lendingType : {id: 'IBD', iso2code: 'XF', value: 'IBRD'} longitude : "116.286" name : "China" region : {id: 'EAS', iso2code: 'Z4', value: 'East Asia & Pacific'} [[Prototype]] : Object
问题原因
直接从data对象取字段是错误的,API返回的是包含两个元素的数组:
- 索引0:分页信息对象
- 索引1:包含单个国家数据的数组
实际的国家数据对象位于*data[1][0]*,而非直接的data。另外,手动创建Subject属于冗余操作,RxJS本身支持直接映射数据流。
修改后的代码
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class ApiService { constructor(private http: HttpClient) { } fetchCountryData(country: string) { const formattedCountry = country.split('-').join(' '); const apiUrl = `http://api.worldbank.org/v2/country/${formattedCountry}?format=json`; return this.http.get(apiUrl); } setCountryData(country: string) { return this.fetchCountryData(country).pipe( map((data: any[]) => { const countryData = data[1][0]; return { country: countryData.name, capital: countryData.capitalCity, income: countryData.incomeLevel.value, region: countryData.adminregion.value, latitude: parseFloat(countryData.latitude), longitude: parseFloat(countryData.longitude) }; }) ); } }
关键修改说明
- 通过
data[1][0]精准定位到国家数据对象 - 使用
pipe+map操作符替代手动Subject,简化代码逻辑并符合RxJS最佳实践 - 可选优化:将经纬度转为数字类型,提取
incomeLevel和adminregion的value字段直接返回可显示文本
内容的提问来源于stack exchange,提问作者Kyle Wilson
相关产品推荐
相关产品推荐

