Assumes, you have a data.json file in the src/app folder of your project with the following values:
[
{
"id": 1,
"name": "Licensed Frozen Hat",
"description": "Incidunt et magni est ut.",
"price": "170.00",
"imageUrl": "https://source.unsplash.com/1600x900/?product",
"quantity": 56840
},
...
]
3 Methods for Reading Local JSON Files
Method 1: Reading Local JSON Files Using TypeScript 2.9+ import Statement
import { Component, OnInit } from '@angular/core';
import * as data from './data.json';
@Component({
selector: 'app-root',
template: `<ul>
<li *ngFor="let product of products">
</li>
</ul>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Angular Example';
products: any = (data as any).default;
constructor(){}
ngOnInit(){
console.log(data);
}
}
Method 2: Reading Local JSON Files Using Angular HttpClient
import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-root',
template: `<ul>
<li *ngFor="let product of products">
</li>
</ul>`,
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Angular Example';
products: any = [];
constructor(private httpClient: HttpClient){}
ngOnInit(){
this.httpClient.get("assets/data.json").subscribe(data =>{
console.log(data);
this.products = data;
})
}
}
Method 3: Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement
If your Angular application goes offline, reading the JSON file with HttpClient will fail. In this case, we have one more method to import local JSON files using the ES6+ import statement which supports importing JSON files.
But first we need to add a typing file as follows:
declare module "*.json" {
const value: any;
export default value;
}
Add this inside a new file json-typings.d.ts
file in the src/app folder.
Now, you can import JSON files just like TypeScript 2.9+.
import * as data from "data.json";