Files
d280-javascript/src/app/services/world-bank.ts

56 lines
1.5 KiB
TypeScript

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError } 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 => {
if (response[0]?.message) {
throw new Error(`World Bank API: ${response[0].message[0].value}`);
}
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'
};
}),
catchError(error => {
console.error(`Failed to fetch data for ${countryCode}:`, error);
return of({
name: 'N/A',
capital: 'N/A',
region: 'N/A',
incomeLevel: 'N/A',
longitude: 'N/A',
latitude: 'N/A'
});
})
);
}
}