0

0

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

聖光之護

聖光之護

发布时间:2025-08-13 22:02:16

|

926人浏览过

|

来源于php中文网

原创

使用 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 代码。

文心快码
文心快码

文心快码(Comate)是百度推出的一款AI辅助编程工具

下载
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('assets/country-codes.json').subscribe(data => {
      this.countryCodes = data;
    });
  }

  getCountryProperties(countryName: string): Observable {
    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('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(operation = 'operation', result?: T) {
    return (error: any): Observable => {

      // 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 请求失败时通知用户。

Could not find country "{{ countryName }}". Please check the spelling or try another country.

  • Name: {{ countryProperties.name }}
  • Capital: {{ countryProperties.capitalCity }}
  • Region: {{ countryProperties.region.value }}
  • Income Level: {{ countryProperties.incomeLevel.value }}
  • Latitude: {{ countryProperties.latitude }}
  • Longitude: {{ countryProperties.longitude }}

注意事项

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

总结

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

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

403

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

528

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

306

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

74

2025.09.10

html版权符号
html版权符号

html版权符号是“©”,可以在html源文件中直接输入或者从word中复制粘贴过来,php中文网还为大家带来html的相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

591

2023.06.14

html在线编辑器
html在线编辑器

html在线编辑器是用于在线编辑的工具,编辑的内容是基于HTML的文档。它经常被应用于留言板留言、论坛发贴、Blog编写日志或等需要用户输入普通HTML的地方,是Web应用的常用模块之一。php中文网为大家带来了html在线编辑器的相关教程、以及相关文章等内容,供大家免费下载使用。

638

2023.06.21

html网页制作
html网页制作

html网页制作是指使用超文本标记语言来设计和创建网页的过程,html是一种标记语言,它使用标记来描述文档结构和语义,并定义了网页中的各种元素和内容的呈现方式。本专题为大家提供html网页制作的相关的文章、下载、课程内容,供大家免费下载体验。

458

2023.07.31

html空格
html空格

html空格是一种用于在网页中添加间隔和对齐文本的特殊字符,被用于在网页中插入额外的空间,以改变元素之间的排列和对齐方式。本专题为大家提供html空格的相关的文章、下载、课程内容,供大家免费下载体验。

241

2023.08.01

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

7

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.7万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 2.7万人学习

CSS教程
CSS教程

共754课时 | 17.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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