Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Load JSON from local

Tags:

json

angular

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:

enter image description here

How I could resolve it?

like image 356
Eladerezador Avatar asked Jun 19 '18 09:06

Eladerezador


4 Answers

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

like image 103
Kamil Naja Avatar answered Sep 24 '22 10:09

Kamil Naja


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));
like image 27
Sachin Shah Avatar answered Sep 25 '22 10:09

Sachin Shah


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,
  ...
},
like image 35
Aravinda Meewalaarachchi Avatar answered Sep 23 '22 10:09

Aravinda Meewalaarachchi


See this article:

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}
like image 32
Ole Avatar answered Sep 24 '22 10:09

Ole