Angular 6 - Load JSON from local

2020-02-08 20:03发布

问题:

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",
  "logo": "fa_logo.png",
  "menu": {
    "background": "orange",
    "link1": "ESCRITOR",
    "link2": "MÚSICO",
    "link3": "AYUDA ADMIN",
    "submenu": {
      "link1": {
        "text1": "novelas",
        "text2": "obras de teatro"
      },
      "link2": {
        "text1": "compositor",
        "text2": "intérprete"
      }
    }
  }
}
  • Way 1: Using Http

This is my service file (general.service.ts)

  getContentJSON() {
    return this.http.get('assets/json/general.json')
    .map(response => response.json());
  }

This way working ok, but shows the next error in the web browser console:

ERROR TypeError: Cannot read property 'menu' of undefined
  • Way 2: Using HttpClient

This is my service file (general.service.ts)

  getContentJSON() {
    return this.httpClient.get("assets/json/general.json");
  }

It does not work because I can not find the general.json file, it goes through the control of the error and it gives me an error 404

This is the component file (app.component.ts)

export class AppComponent implements OnInit {
  contentGeneral: any;

ngOnInit() {
this.getContentJSON();
}

  getContentJSON() {
    this.generalService.getContentJSON().subscribe(data => {
      this.contentGeneral = data;
    }, // Bind to view
    err => {
      // Log errors if any
      console.log('error: ', err);
    });
  }

}

This is the template file (app.component.html):

<a href="#" routerLink="/home" class="linkHome">{{contentGeneral.texthome}}</a>

<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>

This is my actual error:

In app.component.ts, I add the import:

import * as data_json from './assets/json/general.json';

But when I launch ng serve it gives me the following error:

How I could resolve it?

回答1:

The simplest solution:

import "myJSON" from "./myJson"

Important update!

I found, that this method stops working in newest Angular versions, because of this error:

ERROR in src/app/app.weather.service.ts(2,25): error TS2732: Cannot find module './data.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

To make it works, go to the tsconfig.json and add this two, inside

compilerOptions( tsconfig.json ) :

"resolveJsonModule": true,
"esModuleInterop": true,

After change, re-run ng serve.

If you only use the first option, you can get an error like this:

ERROR in src/app/app.weather.service.ts(2,8): error TS1192: Module '"....app/data/data.json"' has no default export.

(I found this very good answer here (https://www.angularjswiki.com/angular/how-to-read-local-json-files-in-angular/))



回答2:

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));


回答3:

For the Angular 2, Angular 4 and Angular 5, you can use following method to load your local .json files to the component.

const data = require('../../data.json');

export class AppComponent  {
    json:any = data;
}

To use require with in your component, you needed to install @types/node by running

npm install @types/node --save-dev

Do the following configuration change under tsconfig.app.json > compilerOptions

"compilerOptions": {
  "types": ["node"],
  ...
},

After Angular 6, you can use direct imports form file system as follows.

import data  from '../../data.json';

export class AppComponent  {
    json:any = data;
}

Do the following configuration change under tsconfig.app.json > compilerOptions

"compilerOptions": {
  ...
  "resolveJsonModule": true,
  "allowSyntheticDefaultImports": true,
  "esModuleInterop": true,
  ...
},


回答4:

See this article:

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}


回答5:

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"


回答6:

you can use the following code snippet:

declare const require;
const locale = localStorage.getItem('locale');
require(`./file.${locale}.json`)


回答7:

Updated answer - Angular 5 Service to read local .json file

In tsconfig.json

"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,



标签: json angular