Abdu Manas C A
Abdu Manas C A

Reputation: 1139

Advantage of typed Get in httpclient

Can anyone explain the advantage of a typed get method in httpClient in angular 5.
Specifically the difference between get(url..); and get<myObject>(url).

What I have understood is that the second method is used to specify the type of data we are getting back. But if the backend api returns a json object, is this needed ?
The Backend api returns a jsonObject in my case. So is there any specific advantage if I specify the second get<myObject>.
Any help is much appreciated.

Thanks

Upvotes: 1

Views: 26

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

If you call get(url), you get back an Observable<Object>, which doesn't tell much about what your service method actually returns, and thus forces every caller of the service to guess, and to use a type assertion to tell TypeScript: trust me, this object is in fact a User, or a Task, or whatever your service actually returns.

If you call get<User>(url), you get back an Observable<User>, which precisely tells what the service returns, and doesn't force all the callers to guess, and frees them from using any type assertion, since you did it already, once, in the service.

Upvotes: 2

Related Questions