Why http?
Most front-end applications communicate with backend services over the HTTP protocol. Angular offers an easy to use HttpClient API for developers.
What is HttpClient?
HttpClient is a powerful tool Angular offers to help REST API connections. Angular HttpClient has and interface that concludes all common used request types as well as hook for interceptors. Angular’s HttpClient returns observables from HTTP method calls. This provides several advantages:
- Observables do not mutate the server response.
- HTTP requests are cancellable through the unsubscribe() method.
- Requests can be configured to get progress event updates.
- Failed requests can be retried easily.
Some most used request types;
- GET
- POST
- PUT
- DELETE
- OPTIONS
What is GET?
GET is used to request data from a specified resource. Angular method constructs an Observable which, when subscribed, will cause the configured GET request to be executed on the server
this.http.get(API).subscribe(data => { console.log(data); }, error => { console.error(error); });
What is POST?
POST is used to send data to a server to create/update a resource. The data sent to the server with POST is stored in the request body of the HTTP request. Angular method constructs an Observable which, when subscribed, will cause the configured POST request to be executed on the server.
this.http.post(API, DATA).subscribe(data => { console.log(data); }, error => { console.error(error); });
What is PUT?
PUT is used to send data to a server to create/update a resource. The difference between POST and PUT is that PUT requests are idempotent. That is, calling the same PUT request multiple times will always produce the same result. In contrast, calling a POST request repeatedly have side effects of creating the same resource multiple times. Angular method constructs an Observable which, when subscribed, will cause the configured PUT request to be executed on the server.
this.http.put(API, DATA).subscribe(data => { console.log(data); }, error => { console.error(error); });
What is DELETE?
The DELETE method deletes the specified resource. Angular method constructs an Observable which, when subscribed, will cause the configured DELETE request to be executed on the server.
this.http.delete(API).subscribe(data => { console.log(data); }, error => { console.error(error); });
What is OPTIONS?
The OPTIONS method describes the communication options for the target resource. Angular method constructs an Observable which, when subscribed, will cause the configured OPTIONS request to be executed on the server.
this.http.options(API).subscribe(data => { console.log(data); }, error => { console.error(error); });