Angular 4&Ionic 3:由于http.get()调用的异步特性,无法从JSON文件填充Ionic菜单

问题描述 投票:0回答:1

我对Angular比较陌生,我的第一个项目是使用Ionic Framework构建移动Web应用程序。无论出于何种原因,我包含所有菜单选项的JSON文件都不会被读取到我的应用程序组件中。

应该是JSON属性数组的我的menu_labels变量返回为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"
            },
.
.
.

我相信问题是我在app.component.ts文件的http.get()类中使用MyApp函数的方式:

// 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项目,因此即使我学习了几门基础知识课程,也可以确定对于有经验的人来说,我的实现看起来很丑陋。

json angular asynchronous ionic3
1个回答
0
投票
return this.http.get('./main-menu.json').map(res=> res.json().pages);
© www.soinside.com 2019 - 2024. All rights reserved.