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

来源:站长论坛作者:广州GEO公司头衔:草根站长
导读:本期聚焦于小伙伴创作的《如何使用Angular和World Bank API通过国家名称获取国家信息》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《如何使用Angular和World Bank API通过国家名称获取国家信息》有用,将其分享出去将是对创作者最好的鼓励。

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

如何使用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

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。