我正在尝试通过两种方式加载本地 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 时,出现以下错误:
我该如何解决?
最佳答案
最简单的解决方案:
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/