-1

In Angular2/Typescript I want to load JSON data from a URL and bind to the Interface/Model. Sometime I want a single data object, other time I want to hold and array of the object. Which one(Interface/Model) should I use and why?

1 Answers1

0

Assuming that the object you are getting back is exactly the same in both object versus array versions then I would always use the array version.

For example let's say the interface is

interface MyApiResponse {
  id: string;
  text: string;
}

In the case where you get an array you can return as is. In the case where you get a single object just wrap it inside an array.

this.http.get(uri, options)
  .map(response => response.json()); 
  .map(data => {
    if (Array.isArray(data)) {
      return data;
    }

    return [data]
   });  // in both cases it will return back as MyApiResponse[]

Streamlining this as an array will simplify your application code as well.

seescode
  • 2,101
  • 15
  • 31