My goal is to fetch data from an external API and display it, but I'm encountering an issue where the data seems to be retrieved "too late" in my code. This delay may be caused by the asynchronous nature of HttpClient.get().
1) Service:
getMetroListObservable(): Observable<Metro[]> {
return this.http.get(this.api)
.map(this.mapper)
.catch(this.handleError);
}
private mapper(current) {
console.log(current); // Data appears here
return current as Metro[];
}
private handleError(error: any) {
return Observable.throw(error.message || error);
}
2) Component using the service:
constructor(private service: MyserviceService) {
this.metroList = [];
}
ngOnInit() {
this.getMetroListObservable();
console.log(this.metroList); // Returns empty array
this.metro = this.metroList[0];
}
getMetroListObservable() {
this.service.getMetroListObservable()
.subscribe(
response => this.metroList = response,
error => this.errorMsg = error
);
}
3) Template for the component:
<p>element: {{metro.idt}}</p>
I want to display the first element of the "metroList" array, but it's currently null because the array is empty. How can I resolve this issue?
Thank you in advance