0

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);
          }
Jeff Zoch
  • 63
  • 1
  • 5
  • Does this answer? http://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class – r3m0t Aug 01 '16 at 21:52
  • No, I dont know what properties the object will have so a typescript class wouldn't suit my needs. I'd rather convert it to a generic javascript object – Jeff Zoch Aug 01 '16 at 21:58
  • Well you can do `as any[]` to do an unsafe cast, but if you're using this function in many places it would be worth putting in a real type for that response – r3m0t Aug 01 '16 at 22:05

1 Answers1

0

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

Community
  • 1
  • 1
r3m0t
  • 1,850
  • 16
  • 21
  • The way I have my app set up, I pass two variables to determine which object to get from backend, and from there populate a google chart. I figured a generic object would be easiest for quickly adding charts and plugging in info, is there a big advantage to using a typescript class that would offset having to create a bunch of different http calls, rather than one unified call? – Jeff Zoch Aug 01 '16 at 22:13
  • Well, you'd get type safety ;) and auto completion in your editor. It's more important for larger projects. – r3m0t Aug 01 '16 at 22:15
  • Your caller knows what the type should be right? You can make this method generic, say `getFromServer(URL_params)` and then do the cast `as T[]`. Then, the return value of this function will be a `Promise`. – r3m0t Aug 01 '16 at 22:19