Angular 6 - 从本地加载 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50924901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:07:39  来源:igfitidea点击:

Angular 6 - Load JSON from local

jsonangular

提问by Eladerezador

I am trying to load a local JSONfile of two ways.

我正在尝试以两种方式加载本地 JSONfile。

This is my json file:

这是我的 json 文件:

{
  "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
  • 方式一:使用Http

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

这是我的服务文件(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:

这种方式工作正常,但在 Web 浏览器控制台中显示下一个错误:

ERROR TypeError: Cannot read property 'menu' of undefined
  • Way 2: Using HttpClient
  • 方式二:使用HttpClient

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

这是我的服务文件(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

它不起作用,因为我找不到general.json文件,它通过错误的控制并给我一个错误404

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

这是组件文件(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):

这是模板文件 ( 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:

在 app.component.ts 中,我添加了导入:

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

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

但是当我启动 ng serve 时,它​​给了我以下错误:

enter image description here

在此处输入图片说明

How I could resolve it?

我该如何解决?

回答by Kamil Naja

The simplest solution:

最简单的解决方案:

import "myJSON" from "./myJson"

Important update!

重要更新!

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

我发现,由于此错误,此方法在最新的 Angular 版本中停止工作:

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

src/app/app.weather.service.ts(2,25) 中的错误:错误 TS2732:找不到模块“./data.json”。考虑使用“--resolveJsonModule”导入带有“.json”扩展名的模块

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

要使其工作,请转到 tsconfig.json 并在里面添加这两个

compilerOptions( tsconfig.json ) :

编译器选项(tsconfig.json):

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

After change, re-run ng serve.

更改后,重新运行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.

src/app/app.weather.service.ts(2,8) 中的错误:错误 TS1192:模块 '"....app/data/data.json"' 没有默认导出。

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

(我在这里找到了这个很好的答案(https://www.angularjswiki.com/angular/how-to-read-local-json-files-in-angular/))

回答by Sachin Shah

By this way...

这样...

import "file" from "./file.json" 

I got red line and got error like module not found by angular.

我得到了红线并得到了错误,比如 angular 找不到模块。

After some RND I got another way which works for me. Hope it may help someone.

经过一些 RND,我得到了另一种对我有用的方法。希望它可以帮助某人。

var data = require('src/file.json');
console.log("Json data : ", JSON.stringify(data));

回答by Aravinda Meewalaarachchi

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

对于Angular 2、Angular 4 和 Angular 5,您可以使用以下方法将本地.json文件加载到组件中。

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

export class AppComponent  {
    json:any = data;
}

To use requirewith in your component, you needed to install @types/nodeby running

require在您的组件中使用with,您需要@types/node通过运行来安装

npm install @types/node --save-dev

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

tsconfig.app.json>下进行以下配置更改compilerOptions

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

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

Angular 6 之后,您可以使用直接导入表单文件系统,如下所示。

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

export class AppComponent  {
    json:any = data;
}

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

tsconfig.app.json>下进行以下配置更改compilerOptions

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

回答by Ole

See this article:

见这篇文章

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

回答by tair yassine

you can use the following code snippet:

您可以使用以下代码片段:

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

回答by Sajeetharan

This happens because you are requesting a JSON file asynchronously, you can handle with safe navigation operator or using ngIf,

发生这种情况是因为您正在异步请求 JSON 文件,您可以使用安全导航操作符或使用 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.

或者简单地在您的组件中导入 JSON 文件并分配 sampleJSON。

import "sampleJSON" from "./sampleJSON"

回答by Surya R Praveen

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

更新答案- Angular 5 Service 读取本地 .json 文件

In tsconfig.json

tsconfig.json 中

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

enter image description here

在此处输入图片说明

回答by Yuvraj Patil

Step 1:Open tsconfig.jsonadd following lines in compilerOptions:

第 1 步:打开tsconfig.json添加以下行compilerOptions

"resolveJsonModule": true,
"esModuleInterop": true

Step 2:import json using following code:

第 2 步:使用以下代码导入 json:

import homeData from './data.json';

Note:This code is tested with Angular 9

注意:此代码已使用 Angular 9 进行测试