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