json - Angular 6 - 从本地加载 JSON

标签 json angular

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

这是我的 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());
  }

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

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 时,出现以下错误:

enter image description here

我该如何解决?

最佳答案

最简单的解决方案:

import "myJSON" from "./myJson"

重要更新!

我发现,这个方法在最新的 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

为了让它工作,转到 tsconfig.json 并在里面添加这两个

编译器选项(tsconfig.json):

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

更改后,重新运行ng serve

如果你只使用第一个选项,你会得到这样的错误:

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

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

关于json - Angular 6 - 从本地加载 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924901/

相关文章:

angular - 知道这是空的

arrays - 元素数组不会被接口(interface)填充

javascript - 来自 Python json.dumps 的 JSON 响应

Ruby:带有转义反斜杠的 JSON.parse

Angular 2 - 将条件样式应用于指令的子 HTML 元素

angular - 如何在使用 jib 时创建 docker-compose.yml 文件?

javascript - 我的网页无法通过 JSON 请求运行

javascript - $.getJSON 在函数内部没有响应

javascript - 将 json 数据添加到现有数组

angular - 在 Angular 6 服务中获取当前路由参数的最佳方法是什么?