There are different ways to read local Json file in Angular. In this example,We’ll also see how to read and display the data from JSON file in angular

 

Different ways to read local JSON file.

Reading JSON file using typescript import statement.
Reading JSON file using Angular HttpClient.
Reading JSON file using ES6+ import statement for offline Angular apps.

Reading JSON file using ES6+ import statement for offline Angular apps

Step 1: Create an Angular application with Angular CLI

ng new read-local-json-angular

Step 2: Create JSON file with dummy data

We’ll create dummy json data files which will be containing list of employees.

{
“employees”: [
{
“id”: “1”,
“name”: “Shaik Iliyas”,
},
{
“id”: “2”,
“name”: “Mullamwar Teju”,
},
{
“id”: “3”,
“name”: “Syed Amrin”,
}
]
}

Now in this app, I will show the data in app component.

Step 3: Import JSON file in the component

Update app.component.ts file, Have a look on the update app.component.ts file.

import { Component } from ‘@angular/core’;
import employees from “../../assets/employees.json”

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
title = ‘json-file-read-angular’;
public employeesList:{name:string}[] = employees;
}

By default, Angular doesn’t read the JSON file in the application. So we need to do some extra stuff for that. So we will create a file named ‘json-typings.d.ts’ inside the app folder of the project. Add below code in it.

declare module “*.json” {
const value: any;
export default value;
}

Step 4: Update Component Template file

Add below code inside app.component.html file

<div style=”text-align:center”>
<h2>
Employee list from local json file…
</h2>
<ul *ngFor=”let item of employeesList”>
<li>
<h3>Employee Name :{{item.name}}</h3>
</li>
</ul>
</div>

Step 5: Run the app

Run the app with npm start over terminal