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

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

关键修改说明

  1. 通过data[1][0]精准定位到国家数据对象
  2. 使用pipe+map操作符替代手动Subject,简化代码逻辑并符合RxJS最佳实践
  3. 可选优化:将经纬度转为数字类型,提取incomeLevel和adminregion的value字段直接返回可显示文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:43:26