I have read some articles about Angular's Http
service, but still I cannot understand some things:
what does http.get('some/string/')
return?
what does http.get('some/string/').map
return? If map
does not return an actual result of http
request, what for do I need to use it?
How can I get actual result of http
request without using map
, observables, toPromise
etc.?
Can I just use Promise
s without toPromise
? If not, how can I use toPromise
to get actual result of http
request?
1) http.get(url)
returns an Observable
which you can use with none or any of the RxJS operators (eg map
, filter
etc - see RxJs docs)
EDIT - as of Angular 4.3 the Http module assumes JSON as deafult so the map(res=>res.json()) call no longer needed!
2) http.get(url).map()
will return a mapped (transformed) Observable
, potentially wrapping a different type, eg Observable<string>
. The exact type depends on the function inside your map
call. Often in Angular 2/4, this function is used to map a response to a javascript object using the .json()
method:
this.http.get(url).map(response => response.json())
which will give you an Observable
wrapping the JS object, eg something like
{user: 'Fred', balance: 65535}
.
To actually 'use' this object/response, you must SUBSCRIBE to the Observable, usually in the calling component (although possibly in the service), and in the subscribe callback you can do what you want with the actual response data, eg log it, pass it to other functions, store as a class member etc:
http.get(url).map(res => res.json()).subscribe(resObject => {
console.log(resObject);
this.user = resObject.user;
this.balance = resObject.balance;
});
Only when subscribe is called is the http request actually made... this is the nature of Rx!
3) You can't, you HAVE to subscribe to the observable. The response from an http call is by nature ASYNCHRONOUS and cannot be simply transformed in synchronous code - you can't just write, e.g.
this.user = http.get(url).fromObservable()
as there is no guarantee the server has responded and provided something to convert and use in synchronous code. In addition, the nature of an observable here is that unless it is subscribed to, the observable will not do anything!
4) You can transform an observable to a promise (although I would avoid it unless you reeeeally love promises as observable are MUCH more powerful) and use .then
if you like...