Ionic 2从嵌套数组中获取数据

时间:2017-11-20 00:23:00

标签: arrays json angular object ionic2

我是Ionic 2 / Angular 2的新手,我一直试图为我正在构建的应用程序修复一个简单的问题,但到目前为止找不到任何解决方案。

我只是想从json文件中获取数据以列出许多类别(电影标题)并在详细信息页面中显示更多细节(制作细节)。细节(导演和制作人)嵌套在json文件中的数组(生产)中。

虽然我可以从json文件中获取胶片图块,但一旦打开详细信息页面,我就无法访问并显示嵌套数据中的数据。

我尝试了很多不同的东西(包括使用for Each循环遍历数组,创建一个生产对象)但似乎没有任何工作。除非我遗漏了一些非常明显的东西?

有人可以帮忙吗? 提前致谢! (我将永远感激任何回应。)

home.ts

export class HomePage {
   films: any;
   productions: any;

  constructor(public navCtrl: NavController, public http: Http) { 
    this.films = this.http.get("assets/data/results-data.json").map(res => res.json());
  }

  openDetails(film) {
    this.navCtrl.push('FilmDetailsPage', {film: film});
  }
}

home.html的

<ion-list>
    <button ion-item *ngFor="let film of films.results" (click)="openDetails(film)">
        {{ film.title }}
    </button>
</ion-list>

results-data.json(摘录)

{
  "results": [
    {
      "title": "A New Hope",
      "production":  [
        {
        "director" : "George Lucas",
        "producer" : "Rick McCallum"
        }
      ]
    },
    {
      "title": "Attack of the Clones",
      "production": [
        {
          "director": "George Lucas",
          "producer": "Kurtz"
        }
      ]
    },

膜detail.html

    <ion-header>
    <ion-navbar color="primary">
        <ion-title>{{ film.title }}</ion-title>  // Working
    </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-card>
        <ion-card-content>
            **{{ production.director }} // Not working**
        </ion-card-content>
    </ion-card>
</ion-content>

膜detail.ts

export class FilmDetailsPage {
  film: any;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.film = this.navParams.get('film');
  }
}

3 个答案:

答案 0 :(得分:0)

以角度

制作ajax请求
this.http.get("assets/data/results-data.json").subscribe(data => {
  // Read the result field from the JSON response.
  this.films = data['results'];
});

答案 1 :(得分:0)

你能尝试一下吗,我认为你的道路存在问题:

<强>膜detail.html

    <ion-header>
    <ion-navbar color="primary">
        <ion-title>{{ film.title }}</ion-title>  // Working
    </ion-navbar>
</ion-header>

<ion-content padding>
    <ion-card>
        <ion-card-content>
            {{ film.production[0].director }}
        </ion-card-content>
    </ion-card>
</ion-content>

答案 2 :(得分:0)

您应该尝试以下操作:

<ion-content padding>
    <ion-card>
        <ion-card-content>
            {{ film.production[0]?.director }}
        </ion-card-content>
    </ion-card>
</ion-content>

我遇到了同样的问题,但是我使用上面的代码解决了我的问题。并且它首先呈现html,这就是为什么会出错并通过使用?来解决问题的原因。

相关问题