Angular 7/8 | HttpClient Service Tutorial to Consume RESTfull API from Server

In this tutorial, we will learn how to quickly integrate HttpClient service in Angular 8 application to consume RESTful API JSON data from the server.

HttpClient enables the communication between client and server through many available methods like get(), post(), put(), delete() etc. We will also add Error handling techniques using RxJS operators at one place in our service.

For demonstrating real-world scenarios, here we will create a Student management application with the following operations:

  • Create a new Student record using the post() method.
  • List/Get Students data to show in a table using get() method.
  • Update any Student data by clicking on Edit put() method.
  • Delete any Student by clicking Delete on table row using delete() method.

HttpClient was introduced after Angular v4.3 so if you have later version you can simply continue

Let’s get started!

First, we will create a new Angular project using the latest version of Angular CLI. If you don’t have it just install by running following NPM command:

Note: Make sure your PC is having NodeJS installed to run NPM command.

Create a new Angular Project

Run following CLI command to create a new Angular project.

We will give a ‘Yes’ to routing and for styling choose ‘CSS’

Now enter the project

Create Components to Show Students Information

To show controls to create new records, list of Students and update existing Student information, we will create new components in our project.

Run the following commands to generate new components to create, update and list students data.

Above ng generate command will automatically inject the components in App’s main module. We also added FormsModule to use [(ngModel)] in our components.

Implement HttpClient in Project

To make remote server calls and consume JSON responses from RESTful API, we will setup HttpClient which is responsible for making a communication channel between application at client and server-side API.

Inject HttpClient Module

Now open app’s main module app.module.ts file to import HttpClientModule from ‘@angular/common/http‘ then add in imports array of @NgModule decorator as shown below:

Update Routing Module

Also, update app-routing.module.ts file to add the route paths for above new added components.

Create Dummy Database using JSON Server

To test our HTTP calls, we will create a mock server on over project root folder with a data.json file acting as an API response from the server.

JSON-server NPM package creates a local server very easily for development purposes.

Run following NPM command to install JSON-server package:

Now place data.json file in folder API/data.json with following data:

You can run server response by running following NPM command:

It will return a smiley face \{^_^}/ hi! with the server data path: http://localhost:3000/students

Also, create an Interface class for Students data by running following command defining the type of values for student item.

then replace the following content in the newly created file “~/models/student.ts

Create Angular Service to Communicate Server using HttpClient methods

For making HTTP calls we will now create a new service which will keep server communication and error handling login separate from rest of the application.

This service will import HttpClient services and method using which we will do CRUD operation on data.

Now create a new service file named api.service.ts under services folder by running following ng generate command:

–skipTests=true option will not generate spec test files.

Now we will add methods in our api.service.ts file for communicating API server through different HttpClient methods. Here we also added RxJS Observable and Operators to handle errors.

handleError() method is handling any error reported by HTTP calls.

For getting JSON response from the server we need to set the ‘Content-Type‘ of every with ‘application/json

Update Component Classes and Templates

To style our components, we will add bootstrap.css file in the <head> section of our index.html file

Creat Student Component

In Create component template we will add a form to take Name, Age, and Address values from the user which will get submitted using submitForm() method.

Update student-create.component.html file with below code:

In the student-create.component.ts file, we will have the submitForm() method to call API service method createItem() to return an Observable. After successfully submitting value we will navigate to list page using Router service.

List Students Component

In list component, we will list all Students in our data.json file in a bootstrap table with rows iterating using *ngFor directive.

The table will also have an Action colum to show Edit and Delete buttons. In Edit action we are simply redirecting to Edit component with item id which we will update in later. The delete button will call delete method in our API service.

Replace the student-list.column.html file with the following code:

In the student-list.component.ts file, we will get the list of all students by calling getList() and also add delete()  to call deleteItem() method in API service.

Update/ Edit Student Item

In Edit component we will get the id of item using ActivatedRoute service then get its details. After that, we will show Form field controls to edit them, after that user can update the value to call the updateItem method in API service.

In the student-edit.component.html file replace following HTML content:

Now in student-edit.component.ts file replace following class component code:

That’s it now you are ready to run your app by hitting following command

Don’t forget to run the json-server to up API server by running following command in a separate console.

If you are using Visual Studio Code terminal then you can hit plus icon to open a new terminal.

 

Find source files on GitHub here

Conclusion: So here we create a demo application to show how to communicate with the server to consume RESTful API. We also created a Mock server with the help of awsome json-server npm package.

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

3
Leave a Reply

avatar
2 Comment threads
1 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Jolly.exeSavagoPriyesh Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Priyesh
Guest
Priyesh

Not working show error: compiler.js:2175 Uncaught Error: Template parse errors: Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’. (” Name ][(ngModel)]=”data.name” placeholder=”Enter Name”> “): ng:///AppModule/[email protected]:62 Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’. (” Age ][(ngModel)]=”data.age” placeholder=”Enter Name”> “): ng:///AppModule/[email protected]:61 Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’. (“abel for=”address”>Address ][(ngModel)]=”data.address” placeholder=”Enter Name”> <button type="submit" cla"): ng:///AppModule/[email protected]:65

Savago
Guest

Thanks!!!