我对 Angular 比较陌生,我的第一个项目是使用 Ionic 框架构建一个移动 Web 应用程序。无论出于何种原因,我的包含所有菜单选项的 JSON 文件都没有被读入我的 App 组件。
我的 menu_labels 变量(应该是 JSON 属性的数组)返回 as undefined
,这意味着我的 *ngFor 指令被跳过。
<ion-list-header *ngFor="let item of menu_labels; let i of index" no-lines no-padding>
在搜索了许多与此类似的问题后,我确定问题可能是由于 HTTP 请求是异步的,并且没有及时返回以供我的 HTML 文档使用。但是,对它们的修复对我的问题不起作用。
我的 JSON 文件的摘录如下所示:
{
"pages":[
{
"title": "Home",
"component": "Homepage"
},
{
"title": "News",
"component": "NewsPage"
},
{
"title": "Mainframe Legacy and Managed Hosting",
"children": [
{
"title": "Mainframe Outsourcing",
"component": "MainframeOutsourcing"
},
.
.
.
我相信问题在于http.get()
我MyApp
在app.component.ts文件的类中使用该函数的方式:
// Save the parsed information from http.get() in menu_labels var
menu_labels: any[];
constructor(public platform: Platform, public statusBar: StatusBar,
public splashScreen: SplashScreen, private http: Http) {
this.initializeApp();
let menu_data = this.getData();
menu_data.subscribe(data => {
this.menu_labels = data;
})
}
getData() {
// parse information from json file containing menu structure
return this.http.get('../assets/main-menu.json').map(res=> res.json().items);
}
或者以我尝试处理app.html文件中异步数据的方式:
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<!-- First Level -->
<ion-list-header *ngFor="let item of menu_labels; let i of index" no-lines no-padding>
<!-- Just Add Button If No Children -->
<ion-item *ngIf="!item.children" no-lines text-wrap>
<button ion-item (click)="openPage(item.component)">{{ item.title }}</button>
</ion-item>
.
.
.
我尝试*ngIf
在<ion-list>
标签中使用来处理异步调用,但结果相同。
谁能告诉我问题出在代码的哪一部分?几个小时以来,我一直在为此挠头。我提前为任何令人痛苦的代码道歉。这也是我的第一个 Angular 项目,所以即使我参加了几门基础课程,我确信我的实现对于更有经验的人来说看起来非常难看。
我认为这条线有问题,
return this.http.get('./main-menu.json').map(res=> res.json().pages);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句