I was doing a test service and from my component when calling the service and wanting to add ".subscribe" it gave me an error that the method was not an observable...
Searching the internet, I managed to solve the problem if I added something like this to my service using .map:
loadAll() {
return this.http.get(this.url)
.map(res => res.json());
}
When adding .map from the component if ".subscribe" worked fine for me.
What I don't understand is what that .map does, I googled but couldn't find any info.
According to what the visual studio code shows me (in English) it is something that takes a result and creates an observable... Could you please clarify what this .map does?
Thank you very much
I recommend you to use the latest version of angular , since http is already deprecated and httpClient is used now .
Example:
Version
ANGULAR <= 4.2
It is used
http
to consume apis; and what it does.map
is transform the result into JSON to be used in your component with subscribe. (in this version of angular yes or yes you should use.map
)Version
ANGULAR >= 4.3
It is used
httpClient
to consume apis; in this version it is no longer necessary to use.map
, since it internally transforms the result into json by default; and in your component you do the same consuming with subscribe.I put the official documentation on how you should implement httpclient to your project: https://angular.io/guide/http
The behavior of .map in an observable is analogous to the behavior of .map in an array : Transform the elements into whatever you want using the function you pass to it.
For example, let's say you have an http call like the one in your example:
I'm assuming it
this.http
's an attribute of the classHttp
, so be warned that its use is now considered deprecated .What happens here is that the call
this.http.get(url)
returns aObservable<Response>
, that is, you have a Response object. But what you are interested in is the response itself, a JSON string with your data. Therefore, with.map(...)
you perform a transformation: each object of type Response emitted is transformed into an object resulting from doing JSON.parse(...) to the response text.I show you an example of its operation with an array:
Now, as I mentioned before, this transformation is necessary because the Http.get method returns a Response, but it is considered outdated because in Angular v4.3 and later there is a class
HttpClient
that also has the get, post, put... and directly returns an already parsed object .