I have rest api which is returning me json array with data. On client side I use this code to create objects from request.
public getNews(): Observable<News[]> {
return this.http.get(this.baseUrl + '/news')
.pipe(
catchError(this.handleError('getNews', []))
)
.map(res => {
let response: any = res;
return response.map((item) => new News(item));
});
}
Subscribing:
this.restProvider.getNews().subscribe((news: News[]) => {
this.news = news;
});
But how can I resolve issue when response is not an array but only single element? Or response is wrong like for example unexpected data from API?
Currently in those situations my application is throwing this error:
response.map is not a function
The following piece of code should help you to handle errors:
this.restProvider.getNews().subscribe((news: News[]) => {
this.news = news;
}, (err) => {
console.log(err);
});
You just need to add the error parameter in the subscribe function.
Now coming on to your first question : What if the response is a single object? -> The signature of the function will always force it to return an array. The error will be generated on the subscription side. A simple solution to this is to change the data type of response.
this.restProvider.getNews().subscribe((news:any) => {
this.news = news;
});
Code, will always return array:
public getNews(): Observable<News[]> {
return this.http.get(this.baseUrl + '/news')
.pipe(
catchError(this.handleError('getNews', []))
)
.map(res => {
if(Array.isArray(res)) {
return res.map((item) => new News(item));
} else {
return [new News(res)];
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With