【发布时间】: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