Angular — Reading data from JSON file using HttpClient
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:
Step 3: Import Http client module in our root module
Import HttpClientModule
in our root module. (app.module.ts
) like below:
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.
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:
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 json
pipe for displaying the content in json format. Please find the HTML snippet below:
Our final output will be like:
Please find the stackblitz link for reference:
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🙏🙏🙏.