4

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

4 Answers 4

9

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;
});
Sign up to request clarification or add additional context in comments.

Comments

4

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)];
     }
  });
}

1 Comment

THIS!!! I had to add the check whether it was an Array or not to my code before it read my passed-through Array as the actual data instead of 'undefined'.
2

When the response is either single object or an array, then it is obviously not consistent behavior and it complicates things. I assume that backend is not under your control.

You can check first the response type to determine if it is an Array or an Object. You can use Array.isArray() for it. Then if the response is not an array, you convert it, like this const res = [response]

From then on, the getNews() should always return an array

Comments

0

I am new right now in Angular and I was confusing using Angular Cli 16 an reading this answers since I found the current (2023) easy solution for doing it using HttpClient. It does the convertion to JSON by itself if json is retoruned, and also the convertion to the right object is easy done.

import { HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import { MyObject } from './myobject';

export class ProductsService {

  constructor(private _http : HttpClient){ }
  
  readMyObjects(): Observable<MyObjects[]>{
    return this._http.get<MyObjects[]>("http://url/to/api/");          
  }
}

That's all

Here I found a simple tutorial and then, obviously, lots of post also on stackoverflow after I found the solution. Here one.

I hope you like it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.