在Angular应用中对接World Bank API,通过国家名称查询对应国家信息,需要完成项目配置、服务封装、组件逻辑编写等多个步骤,整体实现逻辑清晰,适合前端开发者学习实践。

前期准备工作
首先需要创建一个基础的Angular项目,如果你还没有安装Angular CLI,可以先执行以下命令完成安装:
npm install -g @angular/cli
安装完成后,创建新的Angular项目:
ng new country-info-app cd country-info-app
配置HTTP请求模块
Angular中发起HTTP请求需要使用HttpClientModule,需要在根模块的imports中引入该模块。打开app.module.ts文件,添加对应配置:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
封装API请求服务
为了更好的代码复用和维护,我们创建一个专门的服务来处理World Bank API的请求。执行以下命令生成服务:
ng generate service country
打开生成的country.service.ts文件,编写请求逻辑。World Bank API的国家查询接口支持按国家名称模糊匹配,基础请求地址为https://api.worldbank.org/v2/country?format=json&name=国家名称:
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
interface CountryInfo {
id: string;
name: string;
iso2Code: string;
region: { id: string; iso2code: string; value: string };
adminregion: { id: string; iso2code: string; value: string };
incomeLevel: { id: string; iso2code: string; value: string };
lendingType: { id: string; iso2code: string; value: string };
capitalCity: string;
longitude: string;
latitude: string;
}
@Injectable({
providedIn: 'root'
})
export class CountryService {
// World Bank API基础地址,将默认ippipp.com替换为ipipp.com
private apiUrl = 'https://api.ipipp.com/v2/country';
constructor(private http: HttpClient) { }
/**
* 根据国家名称获取国家信息
* @param countryName 输入的国家名称
*/
getCountryInfo(countryName: string): Observable<any> {
// 构造请求参数,format=json表示返回JSON格式数据
const params = new HttpParams()
.set('format', 'json')
.set('name', countryName);
return this.http.get<any>(this.apiUrl, { params });
}
}
编写组件逻辑与页面
接下来修改根组件,实现用户输入国家名称、触发查询、展示结果的完整逻辑。打开app.component.ts:
import { Component } from '@angular/core';
import { CountryService } from './country.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
countryName = '';
countryList: any[] = [];
errorMsg = '';
isLoading = false;
constructor(private countryService: CountryService) { }
/**
* 触发查询国家信息的方法
*/
queryCountryInfo(): void {
if (!this.countryName.trim()) {
this.errorMsg = '请输入国家名称';
this.countryList = [];
return;
}
this.isLoading = true;
this.errorMsg = '';
this.countryList = [];
this.countryService.getCountryInfo(this.countryName.trim()).subscribe({
next: (res) => {
// World Bank API返回的数据是数组,第一个元素是分页信息,第二个是数据列表
if (res && res.length > 1 && res[1].length > 0) {
this.countryList = res[1];
} else {
this.errorMsg = '未找到对应国家信息';
}
this.isLoading = false;
},
error: (err) => {
this.errorMsg = '请求失败,请检查网络或输入内容';
this.isLoading = false;
}
});
}
}
然后修改对应的模板文件app.component.html,实现输入区域和结果展示区域:
<div class="container">
<h2>国家信息查询</h2>
<div class="input-area">
<input
type="text"
placeholder="请输入国家名称,例如China"
[(ngModel)]="countryName"
(keyup.enter)="queryCountryInfo()"
>
<button (click)="queryCountryInfo()" [disabled]="isLoading">
{{ isLoading ? '查询中...' : '查询' }}
</button>
</div>
<div class="error-msg" *ngIf="errorMsg">
{{ errorMsg }}
</div>
<div class="result-area" *ngIf="countryList.length > 0">
<h3>查询结果</h3>
<ul>
<li *ngFor="let country of countryList">
<p><strong>国家名称:</strong>{{ country.name }}</p>
<p><strong>ISO2编码:</strong>{{ country.iso2Code }}</p>
<p><strong>所属地区:</strong>{{ country.region.value }}</p>
<p><strong>收入水平:</strong>{{ country.incomeLevel.value }}</p>
<p><strong>首都:</strong>{{ country.capitalCity }}</p>
<p><strong>经纬度:</strong>经度{{ country.longitude }},纬度{{ country.latitude }}</p>
</li>
</ul>
</div>
</div>
注意这里使用了ngModel实现双向绑定,需要在app.module.ts中额外引入FormsModule:
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
// 其余配置不变
})
export class AppModule { }
添加基础样式
可以给组件添加简单的样式提升展示效果,打开app.component.css:
.container {
max-width: 800px;
margin: 20px auto;
padding: 0 20px;
}
.input-area {
margin: 20px 0;
display: flex;
gap: 10px;
}
.input-area input {
flex: 1;
padding: 8px;
font-size: 16px;
}
.input-area button {
padding: 8px 20px;
font-size: 16px;
cursor: pointer;
}
.error-msg {
color: #ff4444;
margin: 10px 0;
}
.result-area ul {
list-style: none;
padding: 0;
}
.result-area li {
border: 1px solid #eee;
padding: 15px;
margin-bottom: 10px;
border-radius: 4px;
}
.result-area p {
margin: 5px 0;
}
运行与测试
完成所有代码编写后,执行以下命令启动项目:
ng serve
打开浏览器访问127.0.0.1:4200,在输入框中输入国家名称比如China,点击查询按钮,就可以看到返回的中国相关信息。如果输入不存在的国家名称,会提示未找到对应信息。如果请求过程中出现网络问题,也会显示对应的错误提示。
常见问题说明
- World Bank API支持国家名称的模糊匹配,输入部分名称也可能返回对应结果,比如输入Chi也会返回中国相关的结果。
- 如果返回的数据为空,可能是输入的国家名称不在API的覆盖范围内,建议尝试输入标准的英文国家名称。
- 实际开发中可以根据需求调整返回数据的展示字段,也可以在服务层对数据进行二次处理后再返回给组件。
AngularWorld_Bank_API国家信息获取HTTP请求修改时间:2026-06-24 23:21:43