I am trying to load a local JSONfile of two ways.
This is my json file:
{
\"imgsesion\": \"fa_closesesion.png\",
\"texthome\": \"volver a la home
This happens because you are requesting a JSON file asynchronously, you can handle with safe navigation operator or using ngIf,
<div class="submenu" *ngIf="linkWrite.isActive || isSubMenuWriter">
<span class="d-block text-right small">{{contentGeneral?.menu?.submenu?.link1?.text1}}</span>
<span class="d-block text-right small">{{contentGeneral?.menu?.submenu?.link1?.text2}}</span>
</div>
or simply import the JSON file in your component and assign sampleJSON.
import "sampleJSON" from "./sampleJSON"
Create .ts file then copy contents of your json file there and add
export const <objectName> =
something like this
export const faceProfilesSample =
[
{
"id": 1,
"depth": 0,
"burden": null
},
{
"id": 1,
"depth": 1.97,
"burden": 8.58
},
then you can access it by using objectName with import statement like this
import { faceProfilesSample } from "@app/model/face-profiles-sample";
No tsconfig.json changes needed
By this way...
import "file" from "./file.json"
I got red line and got error like module not found by angular.
After some RND I got another way which works for me. Hope it may help someone.
var data = require('src/file.json');
console.log("Json data : ", JSON.stringify(data));
Updated answer - Angular 5 Service to read local .json file
In tsconfig.json
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
Step 1: Open tsconfig.json
add following lines in compilerOptions
:
"resolveJsonModule": true,
"esModuleInterop": true
Step 2: import json using following code:
import homeData from './data.json';
Note: This code is tested with Angular 9
See this article:
import data from './data.json';
export class AppComponent {
json:any = data;
}