首页 > web前端 > js教程 > 正文

使用 Angular 和 World Bank API 通过国家名称检索国家信息

DDD
发布: 2025-08-13 22:04:34
原创
284人浏览过

使用 angular 和 world bank api 通过国家名称检索国家信息

本文档旨在指导开发者如何使用 Angular 框架与 World Bank API 交互,通过国家名称而非 ISO2 代码检索并展示国家信息,包括名称、首都、区域、收入水平、经纬度等关键属性。我们将提供详细的代码示例,并解释如何处理 API 响应数据,从而实现根据国家名称进行查询的功能。

要实现通过国家名称检索 World Bank API 中的国家信息,通常需要以下步骤:

  1. 获取所有国家信息: 首先,你需要从 World Bank API 获取所有国家信息的列表。
  2. 构建国家名称与 ISO2 代码的映射: 创建一个数据结构(例如 JavaScript 对象),将国家名称映射到其对应的 ISO2 代码。
  3. 使用 ISO2 代码查询: 根据用户输入的国家名称,查找其对应的 ISO2 代码,然后使用该代码调用 World Bank API 获取特定国家的信息。

以下是如何在 Angular 应用中实现这些步骤的示例代码:

1. 修改 WorldbankService:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, map } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class WorldbankService {
  private apiUrl = 'http://api.worldbank.org/v2';

  constructor(private http: HttpClient) { }

  getAllCountries(): Observable<any[]> {
    const url = `${this.apiUrl/country}?format=json&per_page=300`;
    return this.http.get<any[]>(url).pipe(
        map((response: any) => response[1]) // Extract the array of countries
    );
  }

  getCountryProperties(countryCode: string): Observable<any> {
    const url = `${this.apiUrl}/country/${countryCode}?format=json`;
    return this.http.get(url).pipe(
        map((response: any) => response[1][0])
    );
  }
}
登录后复制

解释:

  • getAllCountries() 方法用于获取所有国家的列表。 per_page=300确保能获取到所有国家,默认API分页数量较少。使用map操作符提取返回数据中的国家数组。
  • getCountryProperties(countryCode: string)方法接收国家ISO2代码,查询国家信息。

2. 修改 CountryInfoComponent:

NameGPT名称生成器
NameGPT名称生成器

免费AI公司名称生成器,AI在线生成企业名称,注册公司名称起名大全。

NameGPT名称生成器 0
查看详情 NameGPT名称生成器
import { Component, OnInit } from '@angular/core';
import { WorldbankService } from '../worldbank.service';

@Component({
  selector: 'app-country-info',
  templateUrl: './country-info.component.html',
  styleUrls: ['./country-info.component.css']
})
export class CountryInfoComponent implements OnInit {
  countryName = "";
  countryProperties: any = null;
  countryCodeMap: { [key: string]: string } = {};

  constructor(private worldbankService: WorldbankService) {}

  ngOnInit() {
    this.worldbankService.getAllCountries().subscribe(countries => {
      countries.forEach((country: any) => {
        this.countryCodeMap[country.name.toLowerCase()] = country.id;
      });
    });
  }

  getCountryProperties() {
    const countryCode = this.countryCodeMap[this.countryName.toLowerCase()];

    if (countryCode) {
      this.worldbankService.getCountryProperties(countryCode).subscribe(
        (data: any) => {
          this.countryProperties = data;
        },
        (error) => {
          console.error('Error fetching country properties:', error);
          this.countryProperties = null;
        }
      );
    } else {
      alert('Country not found.');
      this.countryProperties = null;
    }
  }
}
登录后复制

解释:

  • countryCodeMap 对象用于存储国家名称和 ISO2 代码的映射关系。
  • ngOnInit() 生命周期钩子用于在组件初始化时获取所有国家信息,并填充 countryCodeMap。 这里将国家名称转换为小写,以确保匹配的准确性。
  • getCountryProperties() 方法首先根据用户输入的国家名称,从 countryCodeMap 中查找对应的 ISO2 代码。 如果找到,则调用 worldbankService.getCountryProperties() 方法获取国家信息。 如果未找到,则显示错误消息。
  • 添加了错误处理,当API调用失败时,将countryProperties设置为null。

3. 更新 country-info.component.html:

<div class="right-column">
    <input type="text" [(ngModel)]="countryName" placeholder="Enter a country name" />
    <button (click)="getCountryProperties()">Enter</button>

    <ul class="properties-list" *ngIf="countryProperties">
        <li>Name: {{ countryProperties.name }}</li>
        <li>Capital: {{ countryProperties.capitalCity }}</li>
        <li>Region: {{ countryProperties.region.value }}</li>
        <li>Income Level: {{ countryProperties.incomeLevel.value }}</li>
        <li>Latitude: {{ countryProperties.latitude }}</li>
        <li>Longitude: {{ countryProperties.longitude }}</li>
    </ul>

    <div *ngIf="countryProperties === null && countryName !== ''">
      No data found for this country.
    </div>
</div>
登录后复制

注意事项:

  • World Bank API 有请求频率限制,请合理控制请求频率,避免被封禁。
  • 为了提高用户体验,可以添加加载指示器,在 API 请求期间显示加载状态。
  • 可以添加输入验证,确保用户输入的国家名称是有效的。
  • 如果需要更精确的匹配,可以考虑使用模糊搜索算法。
  • 由于API返回的是分页数据,需要处理分页问题,确保能获取到所有国家的数据。 上面的示例中使用了 per_page=300 来尝试获取所有国家,但这可能不是一个可靠的长期解决方案,因为国家数量可能会超过300。 更好的方法是循环请求API,直到获取所有数据。

总结:

通过以上步骤,你就可以在 Angular 应用中使用 World Bank API,根据国家名称检索并显示国家信息了。 这个方法的核心在于建立国家名称和ISO2代码的映射关系,然后使用ISO2代码来查询API。 这种方法可以有效地解决 World Bank API 不支持直接通过国家名称查询的问题。 请记住,API 的具体实现可能会随着时间的推移而发生变化,因此请始终参考 World Bank API 的官方文档。

以上就是使用 Angular 和 World Bank API 通过国家名称检索国家信息的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号