值得一看
双11 12
广告
广告

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

使用 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 组件来处理用户输入和显示国家信息。

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 本身不支持直接通过国家名称查询,但我们可以通过获取所有国家的信息并在客户端进行过滤来实现这一功能。这种方法需要权衡性能和用户体验,并根据实际需求进行优化。

温馨提示: 本文最后更新于2025-08-13 22:40:30,某些文章具有时效性,若有错误或已失效,请在下方留言或联系易赚网
文章版权声明 1 本网站名称: 创客网
2 本站永久网址:https://new.ie310.com
1 本文采用非商业性使用-相同方式共享 4.0 国际许可协议[CC BY-NC-SA]进行授权
2 本站所有内容仅供参考,分享出来是为了可以给大家提供新的思路。
3 互联网转载资源会有一些其他联系方式,请大家不要盲目相信,被骗本站概不负责!
4 本网站只做项目揭秘,无法一对一教学指导,每篇文章内都含项目全套的教程讲解,请仔细阅读。
5 本站分享的所有平台仅供展示,本站不对平台真实性负责,站长建议大家自己根据项目关键词自己选择平台。
6 因为文章发布时间和您阅读文章时间存在时间差,所以有些项目红利期可能已经过了,能不能赚钱需要自己判断。
7 本网站仅做资源分享,不做任何收益保障,创业公司上收费几百上千的项目我免费分享出来的,希望大家可以认真学习。
8 本站所有资料均来自互联网公开分享,并不代表本站立场,如不慎侵犯到您的版权利益,请联系79283999@qq.com删除。

本站资料仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END
喜欢就支持一下吧
点赞8赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容