Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Observable to array of objects

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

like image 535
jankes83 Avatar asked Dec 08 '22 15:12

jankes83


2 Answers

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;
});
like image 87
Prasheel Avatar answered Dec 10 '22 04:12

Prasheel


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)];
     }
  });
}
like image 26
Yerkon Avatar answered Dec 10 '22 05:12

Yerkon