In my angular 4 project I am using HTTP Client, when I have a GET call the response is sometimes articulated so I have to do something like:
this.loggedUser.name = response._embedded.agent.name
But in this case I have this error:
Property '_embedded' does not exist on type 'HttpResponse'
I resolve the problem with casting the response to any:
getLoggedUser(url) {
return this.http.get(url, {observe: 'response'})
.map((response) => <any>response);
}
So, Did I have to cast to any all the response? Is this considered good practice, or should I be doing something else?
The
HttpResponse<T>
class does not have any_embedded
property indeed. That is why you get the compiler error, since Typescript statically typed your response toHttpResponse<Object>
(the generic type argument is meant for thebody
property of the response).Casting the response to
<any>
seems like a feasible solution in this case, if you know to expect the_embedded
prop there at any time. A null check might be a nice addition though.Here is the
HttpResponse<T>
typing for reference: