Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Posting, Deleting, and Putting Data in Angular

Dec 5, 2019 • 8 Minute Read

Introduction

In this guide, we're going to look at using HttpClient in Angular to make HTTP requests.

Heire are the main topics that we're going to learn about in the next few minutes:

  • Introduction to HTTP requests
  • Using APIs to make an HTTP request
  • Using HttpClient API to make an HTTP request

Introduction to HTTP requests

An HTTP request is a packet of information which is transferred from source to destination and termed as Client-Server respectively. A client makes the HTTP request, and the server sends the information to the client. HTTP has multiple request methods to make the request and error to indicate the error.

Here are some common HTTP request methods and response status codes.

HTTP Request Methods

  1. OPTIONS - This is used to check all metadata the server requires to ensure a secure request like CORS. It is called automatically before any HTTP request. You can read more about OPTIONS .
  2. GET - This is used to get data from the server.
  3. POST - This is used to send data to the server.
  4. PUT - This is used to update data.
  5. DELETE - This is used to delete data from the server.

Response Status Codes

  1. 200 - This is used to indicate the "OK" message when the HTTP request has completed successfully.
  2. 404 - This is used to indicate a "Resource NOT Found" message when HTTP doesn't find the specified URL at the server.

You can read more about HTTP Response codes and HTTP request methods .

Using APIs to Make an HTTP Request

There are two main types of APIs used to make an HTTP request.

  1. XMLHttpRequest(XHR)
  2. Fetch

Other libraries like Axios and HttpClient use one of the above internally and abstract the complexities around these APIs.

You can read more about XMLHttpRequest and Fetch.

Using HttpClient API to make an HTTP request

The HttpClient in @angular/common/http offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers.

Observable provides better performance over Promise. If you're not familiar with Observable, you can read more about Observable here.

To use the HttpClient in your project, you need to import HttpClient in app.module.ts. After importing, your app.module.ts file will look like following,:

      import { BrowserModule } from "@angular/platform-browser";
import { HttpClientModule } from "@angular/common/http";

import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
    

Then we need to make a service class where we will create the methods to make the HTTP request. You can make the service by using the following command:

      ng g s httpCrudDemo --skipTests=true
    

As you can see, I have used --skipTests=true. because Angular makes two files for service. One is for the business logic and one for unit testing. I'm not going to do any unit testing for now, so I'm skipping the test file.

We're not going to build Backend APIs for this guide; I'm going to use JSONPlaceholder, which is a free API that can test our frontend applications.

Before writing the methods to make the HTTP requests, we need to make the variable of the httpClient in the service class.

      constructor(private httpClient:HttpClient){}
    

This will instantiate the httpClient so we can use it to make the HTTP requests.

It's best practice to divide the whole URL into two parts :

  • Main URL like https://www.yourserver.com
  • EndPoints like /users

So finally our service will look like this:

      import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpCrudDemoService {
  url: string;

constructor(private httpClient: HttpClient) {
  this.url = "https://jsonplaceholder.typicode.com";
}
    

In the following section, I'm going to write the service methods to create, read, update, and delete the post.

Get All the Posts

      public getPosts(){
  let endPoints=""
    this.httpClient.get(this.url+endPoints).subscribe(data => {
    console.log(data);
  });
}
    

The GET method of the HTTP request fetches the data from the service and gives an array of objects. It takes only one parameter i.e., Backend Service URL. GET method will provide the data in JSON format that we need to convert in typescript object. But thanks to HTTPClient it converts the data from JSON to an observable form for us. To extract the data from the observable, we need to use the subscribe method of rxjs, which will give the data in a typescript/javascript object which we can use in any other function.

Get Post by ID

      public getPostById() {
  let id: number = 1;
  let endPoints = "/posts/" + id;
  this.httpClient.get(this.url + endPoints).subscribe(data => {
    console.log(data);
  });
}
    

In the above function, I'm fetching the data for one specific ID. In this case, only one object is returned instead of an array of objects.

Add New Post

      public addPost(postData: Object) {
  let endPoints = "/posts"
  this.httpClient.post(this.url + endPoints, postData).subscribe(data => {
    console.log(data);
  });
}
    

The POST method is used for sending the data to the server. It takes two parameters, the service URL and the request body. In many cases, the servers send the ID of the object in response to confirm that your data has been processed by the server and the object has been created successfully.

Update the Post

      public updatePost(postData: Object) {
  let endPoints = "/posts/1"
  this.httpClient.put(this.url + endPoints, postData).subscribe(data => {
    console.log(data);
  });
}
    

The PUT method is used for updating an object which is already saved in the database. It also requires two parameters, first the URL and second request body. For updating the object, we need to pass the object ID in the URL as a route parameter.

Delete the Post

      public deletePost() {
  let endPoints = "/posts/1"
  this.httpClient.delete(this.url + endPoints).subscribe(data => {
    console.log(data);
  });
}
    

The DELETE method only requires the URL which has the ID of the object. It checks the ID and deletes the data from the database. But in a real-world application it soft deletes the data, meaning data is not be removed from the server permanently, it just gets inactivated, mainly for reporting purposes.

To make the HTTP request, you should always look for the headers because in many cases the server will only accept the request from an authorized client. In such cases an authorization or access token must be passed in the authorization header.

Conclusion

HttpClient is one of the best APIs to make HTTP requests. It returns an Observable, but if you want to return a Promise that can also be done using HttpClient. It is best practice to return an Observable and subscribe it in other functions.

That's it from this guide. I hope you are familiar with HttpClient now. Don't wait anymore—break the JSONPlaceholder servers.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author