Angular 6 - Load JSON from local

前端 未结 9 2463
南笙
南笙 2020-12-14 04:26

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         


        
相关标签:
9条回答
  • 2020-12-14 05:02

    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,
      ...
    },
    
    0 讨论(0)
  • 2020-12-14 05:03

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

    0 讨论(0)
  • 2020-12-14 05:03

    you can use the following code snippet:

    declare const require;
    const locale = localStorage.getItem('locale');
    require(`./file.${locale}.json`)
    
    0 讨论(0)
提交回复
热议问题