Phase C: Create World Bank API service with HttpClient
This commit is contained in:
40
src/app/services/world-bank.ts
Normal file
40
src/app/services/world-bank.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
export interface CountryData {
|
||||
name: string;
|
||||
capital: string;
|
||||
region: string;
|
||||
incomeLevel: string;
|
||||
longitude: string;
|
||||
latitude: string;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class WorldBankService {
|
||||
private apiUrl = 'https://api.worldbank.org/v2/country';
|
||||
|
||||
constructor(private http: HttpClient) { }
|
||||
|
||||
getCountryData(countryCode: string): Observable<CountryData> {
|
||||
const url = `${this.apiUrl}/${countryCode}?format=json`;
|
||||
|
||||
return this.http.get<any>(url).pipe(
|
||||
map(response => {
|
||||
const country = response[1][0];
|
||||
return {
|
||||
name: country.name || 'N/A',
|
||||
capital: country.capitalCity || 'N/A',
|
||||
region: country.region?.value || 'N/A',
|
||||
incomeLevel: country.incomeLevel?.value || 'N/A',
|
||||
longitude: country.longitude || 'N/A',
|
||||
latitude: country.latitude || 'N/A'
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user