Making API requests with Angular 2 Http service and RxJS is very similar to working with promises in Angular 1.x.
Use the Http class to make requests. The Http class exposes the methods for issuing HTTP requests GET
, POST
, PUT
, DELETE
, PATCH
, HEAD
requests via corresponding methods. It also exposes a generic request
method for issuing any kind of HTTP request.
All methods of the Http
class return an Observable<Response>
, to which you can apply RxJS operations. You call the .subscribe()
method and pass in a function to be called when data is returned in the Observable stream.
The Observable stream for a request contains only one value - the Response
, and completes/settles when the HTTP request is completed succesfully, or errors/faults if an error is thrown.
Note, the observables returned by the Http
module are cold, which means if you subscribe to the observable multiple times, the originating request will be executed once for each subscription. This can happen if you want to consume the result in multiple components of your application. For GET requests this might just cause some extra requests, but this can create unexpected results if subscribe more than once to PUT or POST requests.