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

使用 Angular 和 World Bank API 通过国家名称获取国家信息

聖光之護
发布: 2025-08-13 22:02:16
原创
885人浏览过

使用 angular 和 world bank api 通过国家名称获取国家信息

本文档旨在指导开发者如何使用 Angular 应用程序通过国家名称从 World Bank API 获取国家信息。通常,World Bank API 使用 ISO 2 代码进行查询。本文将介绍如何绕过此限制,通过国家名称实现查询功能,并展示如何在 Angular 应用中实现这一功能。

简介

World Bank API 提供了一个强大的接口来访问各种国家的信息。然而,它主要依赖于 ISO 2 代码进行国家识别。如果你的应用程序需要通过国家名称进行搜索,则需要采取一些额外的步骤。以下是一种可能的解决方案:

解决方案概述

由于 World Bank API 本身不支持直接通过国家名称进行搜索,因此我们需要创建一个国家名称到 ISO 2 代码的映射。这可以通过维护一个包含所有国家名称及其对应 ISO 2 代码的查找表来实现。

步骤 1:创建国家名称到 ISO 2 代码的映射

首先,你需要一个包含国家名称和 ISO 2 代码对应关系的 JSON 文件。你可以手动创建一个,也可以从公开的数据源获取。以下是一个简单的示例 country-codes.json 文件:

[
  { "name": "United States", "iso2Code": "US" },
  { "name": "Canada", "iso2Code": "CA" },
  { "name": "France", "iso2Code": "FR" },
  { "name": "Germany", "iso2Code": "DE" },
  { "name": "United Kingdom", "iso2Code": "GB" }
  // ... 更多国家
]
登录后复制

将此文件放置在你的 Angular 项目的 assets 文件夹中。

步骤 2:修改 Angular Service

修改你的 WorldbankService 以加载 country-codes.json 文件,并创建一个函数来根据国家名称查找 ISO 2 代码。

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

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

  constructor(private http: HttpClient) {
    this.loadCountryCodes();
  }

  private loadCountryCodes() {
    this.http.get<any[]>('assets/country-codes.json').subscribe(data => {
      this.countryCodes = data;
    });
  }

  getCountryProperties(countryName: string): Observable<any> {
    const iso2Code = this.getIso2Code(countryName);
    if (iso2Code) {
      const url = `${this.apiUrl}/${iso2Code}?format=json`;
      return this.http.get(url).pipe(
        map((data: any) => data[1][0]),
        catchError(this.handleError<any>('getCountryProperties'))
      );
    } else {
      console.error(`ISO 2 code not found for country: ${countryName}`);
      return of(null); // 返回一个空的 Observable
    }
  }

  private getIso2Code(countryName: string): string | undefined {
    const country = this.countryCodes.find(c => c.name.toLowerCase() === countryName.toLowerCase());
    return country ? country.iso2Code : undefined;
  }

    /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}
登录后复制

代码解释:

  • loadCountryCodes(): 从 assets/country-codes.json 加载国家代码映射。
  • getCountryProperties(countryName: string): 接受国家名称作为输入,使用 getIso2Code() 查找对应的 ISO 2 代码,然后使用 ISO 2 代码调用 World Bank API。
  • getIso2Code(countryName: string): 在 countryCodes 数组中查找与给定国家名称匹配的 ISO 2 代码。
  • handleError(): 一个通用的错误处理函数,用于在 API 请求失败时提供反馈,并避免应用程序崩溃。

步骤 3:修改 Component

在你的 country-info.component.ts 中,你只需要调用 WorldbankService 的 getCountryProperties 方法,无需修改太多。

import { Component } 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 {
  countryName = "";
  countryProperties: any = null;

  constructor(private worldbankService: WorldbankService) {}

  getCountryProperties() {
    this.worldbankService.getCountryProperties(this.countryName).subscribe(
      (data: any) => {
        this.countryProperties = data;
      },
      (error) => {
        console.error('Error fetching country properties:', error);
        this.countryProperties = null; // 清空数据,显示错误信息
      }
    );
  }
}
登录后复制

步骤 4:修改 HTML 模板

在 country-info.component.html 中,添加一个错误提示信息,以便在没有找到国家或 API 请求失败时通知用户。

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

    <div *ngIf="!countryProperties && countryName">
        <p>Could not find country "{{ countryName }}". Please check the spelling or try another country.</p>
    </div>

    <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>
登录后复制

注意事项

  • 数据源: country-codes.json 文件需要维护更新,以确保包含所有需要的国家和正确的 ISO 2 代码。
  • 错误处理: 添加适当的错误处理机制,以便在 API 请求失败或未找到国家时通知用户。
  • 性能: 对于大型国家列表,考虑使用更高效的查找算法,例如哈希表。
  • 大小写: 在比较国家名称时,忽略大小写,以提高用户体验。
  • 模糊匹配: 如果需要支持模糊匹配,可以使用字符串相似度算法来查找最匹配的国家。

总结

通过创建一个国家名称到 ISO 2 代码的映射,我们可以绕过 World Bank API 的限制,实现通过国家名称进行查询的功能。这种方法需要在客户端维护一个查找表,并进行适当的错误处理。记住要定期更新你的 country-codes.json 文件,以确保数据的准确性。

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

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

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

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

Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号