I am now building my front-end now on Angular and for the life of me, I cannot see what is causing this error. I am using Node.js as my backend. Below is my code.
country.ts
export class Country {
id?: string;
name?: string;
icon?: string;
imageFlag?: string;
}
countries.services.ts
export class CountriesService {
constructor(private http: HttpClient) {}
getCountries(): Observable<Country[]> {
return this.http.get<Country[]>('http://127.0.0.1:3300/api/v1/countries/');
}
}
countries-list.component.ts
export class CountriesListComponent implements OnInit {
countries: Country[] = [];
constructor(private countriesService: CountriesService) {}
ngOnInit(): void {
this.countriesService.getCountries().subscribe((amazwe) => {
this.countries = amazwe;
console.log(amazwe);
});
}
}
My console on console.log(amazwe)
depicts the below
{
"status": "success",
"results": 7,
"data": {
"data": [
{
"_id": "61c4827a69a96679469adac2",
"name": "Botswana",
"icon": "Safari iCON",
"imageFlag": "Botswana Flag",
"__v": 0,
"id": "61c4827a69a96679469adac2"
},
{
"_id": "61c482ab69a96679469adac4",
"name": "South Africa",
"icon": "Safari iCON",
"imageFlag": "South Africa Flag",
"__v": 0,
"id": "61c482ab69a96679469adac4"
},
{
"_id": "61c482c369a96679469adac6",
"name": "Namibia",
"icon": "Safari iCON",
"imageFlag": "Namibia Flag",
"__v": 0,
"id": "61c482c369a96679469adac6"
},
{
"_id": "61c482f569a96679469adac8",
"name": "Mozambique",
"icon": "Safari iCON",
"imageFlag": "Mozambique Flag",
"__v": 0,
"id": "61c482f569a96679469adac8"
},
{
"_id": "61c4831769a96679469adaca",
"name": "Zimbabwe",
"icon": "Safari iCON",
"imageFlag": "Zimbabwe Flag",
"__v": 0,
"id": "61c4831769a96679469adaca"
},
{
"_id": "61c4832f69a96679469adacc",
"name": "Zambia",
"icon": "Safari iCON",
"imageFlag": "Zambia Flag",
"__v": 0,
"id": "61c4832f69a96679469adacc"
},
{
"_id": "61c4836369a96679469adace",
"name": "Tanzania",
"icon": "Safari iCON",
"imageFlag": "Tanzania Flag",
"__v": 0,
"id": "61c4836369a96679469adace"
}
]
}
}
Your response data to class/interface is as below:
export interface ICountryListResponse {
status: string;
results: number;
data: { data: Country[] };
}
Modify your CountriesService.getCountries()
to expect received ICountryListResponse
data response and next with .pipe(map)
to return the result as Observable<Country[]>
.
countries.services.ts
import { map } from 'rxjs/operators';
getCountries(): Observable<Country[]> {
return this.http
.get<ICountryListResponse>('http://127.0.0.1:3300/api/v1/countries/')
.pipe(map((response: ICountryListResponse) => response.data.data));
}