【问题标题】:Angular 6 - Load JSON from localAngular 6 - 从本地加载 JSON
【发布时间】:2018-11-28 05:03:23
【问题描述】:

我正在尝试以两种方式加载本地 JSON 文件。

这是我的 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"
      }
    }
  }
}
  • 方式一:使用Http

这是我的服务文件 (general.service.ts)

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

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

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

这是我的服务文件 (general.service.ts)

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

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

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

}

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

这是我的实际错误:

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

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

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

我该如何解决?

【问题讨论】:

  • 还有另一种方法。您可以在 .ts 文件中创建一个导出的 json 并将其导入到您的组件中。然后您可以访问组件中的 json

标签: json angular


【解决方案1】:

最简单的解决方案:

import "myJSON" from "./myJson"

重要更新!

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

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

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

compilerOptions(tsconfig.json):

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

修改后重新运行ng serve。

如果只使用第一个选项,可能会出现如下错误:

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

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

【讨论】:

  • ./src/app/app.component.ts Module not found: Error: Can't resolve './assets/json/general.json'
  • 这是新的导入:import * as json from './assets/json/general.json';
  • 我已经看到我必须在文件 typings.d.ts 中添加声明代码,但是 Angular 6 中的这个文件我认为它不再存在了
  • 关于在 Angular 6 中添加 typings.d.ts 的重要一点 stackoverflow.com/a/51040468/1845580 您必须创建文件,然后将自定义类型文件添加到 tsconfig.json 中的 typeRoots "typeRoots": ["node_modules /@types", "src/typings.d.ts"],
  • esModuleInterop 不再需要 github.com/Microsoft/TypeScript/issues/25400
【解决方案2】:

发生这种情况是因为您正在异步请求 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>

或者直接在组件中导入 JSON 文件并分配 sampleJSON。

import "sampleJSON" from "./sampleJSON"

【讨论】:

    【解决方案3】:

    这样……

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

    我得到了红线,并且出现了诸如 Angular 找不到模块之类的错误。

    经过一些 RND,我找到了另一种适合我的方法。希望它可以帮助某人。

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

    【讨论】:

    • 我猜应该是JSON.stringify(data)。
    • 哎呀,这是拼写错误。 @UlianaPavelko
    • 谢谢。这种方法对我有用。我得到了“Typescript : require statement not part of an import statement”并通过将解决方案更改为 import data = require('your_file.json') 来解决它
    • 在 Angular 中使用“require”需要以下注意事项 - stackoverflow.com/questions/43104114/…
    【解决方案4】:

    可以使用以下代码sn-p:

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

    【讨论】:

      【解决方案5】:

      See this article:

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

      【讨论】:

        【解决方案6】:

        更新答案 - Angular 5 Service to read local .json file

        在 tsconfig.json

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

        【讨论】:

          【解决方案7】:

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

          const data = require('../../data.json');
          
          export class AppComponent  {
              json:any = data;
          }
          

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

          npm install @types/node --save-dev
          

          在tsconfig.app.json>compilerOptions下做如下配置更改

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

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

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

          在tsconfig.app.json>compilerOptions下做如下配置更改

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

          【讨论】:

            【解决方案8】:

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

            "resolveJsonModule": true,
            "esModuleInterop": true
            

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

            import homeData from './data.json';
            

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

            【讨论】:

              【解决方案9】:

              创建 .ts 文件,然后将 json 文件的内容复制到那里并添加

              export const <objectName> =
              

              类似的东西

              export const faceProfilesSample =
              [
              {
                "id": 1,
                "depth": 0,
                "burden": null
              },
              {
                "id": 1,
                "depth": 1.97,
                "burden": 8.58
              },
              

              然后你可以使用 objectName 和这样的 import 语句来访问它

              import { faceProfilesSample } from "@app/model/face-profiles-sample";
              

              无需更改 tsconfig.json

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2019-04-04
                • 2019-05-24
                • 2019-01-08
                • 2018-12-23
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多