Angular Load json data in Restful API

In this article, I am going to show you how to display JSON data. We will fetch the data in JSON format from the RESTful api.

We will follow these steps to do this

  1. Create Angular Project
  2. Create a component name Products
  3. Create a Angular Service to fetch data
  4. Add HTTPClient module to AppModule
  5. Show list of products

Create Angular Project

I am going to use the Angular CLI to create a new project. If you have not already installed Angular CLI please look at this post

We will create a project name stock. You can run the following command in your terminal

You can open the project with Visusl Studio Code and your project will be like this

Create Products Component

Now I am going to create a component named products and fetched data from the RESTful API is going to be stored in this component
You can run the following command in your terminal

Angular will generate following files for you

CREATE src/app/products/products.component.css (0 bytes)
CREATE src/app/products/products.component.html (27 bytes)
CREATE src/app/products/products.component.spec.ts (642 bytes)
CREATE src/app/products/products.component.ts (277 bytes)
UPDATE src/app/app.module.ts (483 bytes)

Create a Angular Service

We are going to fetch the data from REST endpoint via Angular Service. You can use the HTTP Client library of Angular to fetch the data

First, we will create our ProductService with following command

This will create the src/app/product.service.ts file where you can add the code to fetch data

You have to import the HttpClient and inject the HttpClient to constrctor.
Then you have the getProducts method which will fetch the products from API. Finally I am going to inject HttpClient to the constructor so that I can use the get method of the HttpClient library inside the getProduct() method

Note:

If you have modules in your app and you do need to access this ProductService from those modules, you have to add this ProductService to app.module.ts file.

Add HTTPClientModule to AppModule

You can add following code to the app.module.ts file

Show list of products

I need to load the products from src/app/products/products.component.ts. So you can import the ProductService and inject ProductService to constructor then call the getProducts method inside the ngOnInit()

Now you can edit the src/app/products/products.component.html with following code using ngFor directive

Finally you can update thesrc/app/app.component.html file with following code