Jeff Zoch Jeff Zoch - 4 months ago 60
JSON Question

Whats the best way to cast JSON to generic Object[] in angular 2 typescript?

Not sure if this works as intended, but I want to convert a blob of json into an array of generic objects (the objects are malleable and can change depending on my URL). Should I use JSON.parse(res.json().data) instead? Thanks.

return this.http.get(URL)
.toPromise()
.then(response => response.json().data as Object[])
.catch(this.handleError);
}

Answer

The problem with your solution is that the Object type doesn't have any members (other than the usual) so any attempt to access specific properties from your JSON like id etc will create an error.

The correct way is as any[]:

  return this.http.get(URL)
                        .toPromise()
                        .then(response => response.json().data as any[]) 
                        .catch(this.handleError);
           }

This will let you access everything that was in the JSON response (as well as everything that wasn't in the JSON response. You'll get an error at runtime).

It would be better to cast the result to a specific type, see How do I cast a JSON object to a typescript class