0

I have a webapi that returns an array like:

[
 {"id":1,"name": "name" }
]

When I am doing get

http.get<MyType[]>('url')
.subscribe(data => {
  // data = [Object]
})

The data is not getting converted in my object. It is stays like [Object]. I can access the data like data[0].id, data[0].name but the official httpclient doc saying that I can typecheck the data which is fine. But how would you convert the whole array in to your type in my case MyType[] ?

I am using angular 4.3+ HttpClient

1
  • Can you share more of your code? Commented Aug 15, 2017 at 2:02

1 Answer 1

1

I'm assuming this is your question:

Do I have to access the data like data[0].id, data[0].name ?

Yes you have, because data is an array.

Besides, you said:...

The data is not getting converted in my object. It is stays like [Object]... Any ideas how to convert the response in to MyType[] ?

I'm not sure you understand what a Type System is. TypeScript is a Type System. It plays no role in runtime. By the time you compile TypeScript (which you have to do in order to run it), there's no TypeScript anymore. If you see TypeScript in runtime, that's just a representation so you can make sense of your code. This is called source-maps. In runtime, it's all JavaScript.

That being said, there're no objects being converted from one type to the other in runtime. The only conversion that exists is something like (foo as any).bar()), but again, this only exists until you compile so the Type System can know that foo has bar().

Your response should already be MyType[]. If you see [Object] in runtime, that's because Chrome Dev Tools is calling toString() on MyType, which hasn't been overriden, so it will display [Object].

Sign up to request clarification or add additional context in comments.

1 Comment

just created a new question that actually different version of this one stackoverflow.com/questions/45686553/… as this one was too generic and not enough specific

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.