Angular 2 Angular RXJS Subjects and Observables with API requests

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

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.



Got any Angular 2 Question?