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

使用 Angular 调用 World Bank API 并通过国家名称显示信息

心靈之曲
发布: 2025-08-13 22:22:01
原创
933人浏览过

使用 angular 调用 world bank api 并通过国家名称显示信息

本文介绍了如何使用 Angular 应用调用 World Bank API,并通过国家名称而非 ISO2 代码来检索和显示国家信息。文章将提供关键代码示例,并详细解释如何构建服务、组件以及 HTML 模板,从而实现根据用户输入的国家名称动态展示国家属性的功能。

理解 World Bank API

World Bank API 允许开发者访问丰富的世界银行数据。通常,API 使用 ISO2 国家代码进行查询。但是,如果我们需要通过国家名称进行查询,则需要进行一些处理。

解决方案概述

由于 World Bank API 本身不直接支持通过国家名称进行搜索,我们需要先获取所有国家的信息,然后通过 Angular 应用在客户端进行过滤。

步骤 1: 创建 Angular 服务

首先,创建一个 Angular 服务来与 World Bank API 进行交互。这个服务将负责获取所有国家的信息。

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

@Injectable({
  providedIn: 'root'
})
export class WorldbankService {
  private apiUrl = 'http://api.worldbank.org/v2/country?format=json&per_page=300'; // 获取所有国家,per_page 设置为最大值

  constructor(private http: HttpClient) { }

  getAllCountries(): Observable<any[]> {
    return this.http.get<any>(this.apiUrl).pipe(
      map((data: any) => data[1]) // API 返回的数据结构是数组,国家信息在第二个元素中
    );
  }

  getCountryProperties(countryName: string, countries: any[]): any {
    const foundCountry = countries.find(country => country.name.toLowerCase() === countryName.toLowerCase());
    return foundCountry;
  }
}
登录后复制

代码解释:

  • getAllCountries() 方法从 World Bank API 获取所有国家的信息。per_page=300 参数用于获取所有国家,避免分页。
  • getCountryProperties() 方法接收国家名称和国家数组作为参数,然后在数组中查找匹配的国家。注意这里使用了 toLowerCase() 进行大小写不敏感的匹配。

步骤 2: 创建 Angular 组件

接下来,创建一个 Angular 组件来处理用户输入和显示国家信息。

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;
  allCountries: any[] = [];

  constructor(private worldbankService: WorldbankService) {}

  ngOnInit(): void {
    this.worldbankService.getAllCountries().subscribe(
      (data: any[]) => {
        this.allCountries = data;
      }
    );
  }

  getCountryProperties() {
    const foundCountry = this.worldbankService.getCountryProperties(this.countryName, this.allCountries);
    this.countryProperties = foundCountry;
  }
}
登录后复制

代码解释:

  • ngOnInit() 生命周期钩子在组件初始化时调用 getAllCountries() 方法,并将所有国家的信息存储在 allCountries 数组中。
  • getCountryProperties() 方法调用 worldbankService.getCountryProperties() 方法,传入用户输入的国家名称和 allCountries 数组,查找匹配的国家,并将结果存储在 countryProperties 变量中。

步骤 3: 修改 HTML 模板

修改 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 *ngIf="countryProperties.name">Name: {{ countryProperties.name }}</li>
        <li *ngIf="countryProperties.capitalCity">Capital: {{ countryProperties.capitalCity }}</li>
        <li *ngIf="countryProperties.region?.value">Region: {{ countryProperties.region.value }}</li>
        <li *ngIf="countryProperties.incomeLevel?.value">Income Level: {{ countryProperties.incomeLevel.value }}</li>
        <li *ngIf="countryProperties.latitude">Latitude: {{ countryProperties.latitude }}</li>
        <li *ngIf="countryProperties.longitude">Longitude: {{ countryProperties.longitude }}</li>
    </ul>
    <p *ngIf="countryProperties === null && countryName !== ''">No country found with that name.</p>
</div>
登录后复制

代码解释:

  • *ngIf 指令用于有条件地显示国家属性。
  • 添加了当未找到国家时显示的提示信息。
  • 使用了 countryProperties.region?.value 和 countryProperties.incomeLevel?.value 避免在这些属性为空时报错。

注意事项

  • 性能: 获取所有国家的信息可能需要一些时间,特别是第一次加载时。可以考虑使用本地存储或缓存来提高性能。
  • 错误处理: 添加适当的错误处理机制,例如在 API 请求失败时显示错误消息。
  • API 限制: World Bank API 可能有请求限制。确保遵守 API 的使用条款。
  • 用户体验: 可以添加加载指示器,让用户知道正在加载数据。
  • 数据一致性: 确保用户输入的国家名称与 API 返回的国家名称一致。可以使用模糊匹配或建议列表来提高用户体验。

总结

通过以上步骤,我们可以创建一个 Angular 应用,通过国家名称从 World Bank 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号