Sitemap
Better Programming

Advice for programmers.

Angular

How To Read a JSON File From Assets in Angular

4 min readOct 17, 2022

--

Example available at https://jsonplaceholder.typicode.com/. You can use https://jsoneditoronline.org/ to experiment with JSON data.
Example available at https://jsonplaceholder.typicode.com/. You can use https://jsoneditoronline.org/ to experiment with JSON data.

Read a JSON File From Assets in Angular

1. Using the import statement

import * as jsonData from '../assets/data.json';
// tsconfig.json{
"compileOnSave": false,
"compilerOptions": {
...
"resolveJsonModule": true,
...
},
"angularCompilerOptions": {
...
}
}
Console.log of data.json
Console.log of data.json

2. Using Angular HttpClient

this.httpClient.get(this.URL).subscribe(console.log);
Console.log of data.json
Console.log of data.json

3. Other ways to read a JSON file from assets in Angular

3.1 Add a typing file — json-typings.d.ts

//  json-typings.d.tsdeclare module "*.json" {
const value: any;
export default value;
}

3.2 Use the fetch API

// app.component.tsngOnInit(): void {
fetch('./assets/data.json').then(res => res.json())
.then(console.log); // do something with data
}

3.3 Use Angular JsonPipe

<p>{{ data | json}}</p>
<pre>{{ data | json}}</pre>
<pre>{{ data | json}}</pre>
<pre>{{ data | json}}</pre>

--

--

Lo Zarantonello
Lo Zarantonello

Written by Lo Zarantonello

Software Engineer | Instructor | Life Form Exploring His Surroundings

Responses (1)