Angular — Reading data from JSON file using HttpClient

anoop r warrier
3 min readJul 21, 2022

--

In this post, we will discuss on how to read data from a JSON file which is there locally in our assets folder within our repo. So without wasting much time let’s start.

Step 1: Create a new Angular Project

Create a angular project using CLI command:

ng new json-read-example

Step 2: Create a JSON file with some user information under assets folder

Create a data.json file with some user details under our assets folder. Lets have some user information something like:

data.json

Step 3: Import Http client module in our root module

Import HttpClientModule in our root module. (app.module.ts) like below:

app.module.ts

Step 4: Inject Http client in our component

InjectHttpClient in our component (app.component.ts). We are using HTTP get method read the json data from our data.json . Below is the snippet to inject HttpClient.

Injecting HttpClient in app.component.ts

Step 5: Using OnInit lifecycle hook, get the JSON data using http

Now we are going to implement the OnInit interface and we make an Http GET request to read the data. Please refer the snippet below:

app.component.ts

Here, the response that we get is assigned to a property UserInfo and finally we display the information in out view in next step.

Step 6: Display user details

We could use interpolation and jsonpipe for displaying the content in json format. Please find the HTML snippet below:

app.component.html

Our final output will be like:

Final view of our implementation

Please find the stackblitz link for reference:

https://stackblitz.com/edit/angular-ivy-phwyr1

Summary

Using local JSON files in Angular applications is very easy, And it’s very useful when we need to show some static data at front end.

Thank you everyone for reading the article. I hope you enhanced your some knowledge in Angular. Please support this article with your support to help it spread to a wider audience🙏🙏🙏.

--

--