如何循环嵌套的JSON数据

时间:2018-01-15 17:12:51

标签: json angular

我试图循环浏览json数据,以便每个元素。我需要深入了解详细数据,然后在循环中通过f1,f2进入div。我尝试过使用索引但是没有用。我也不知道从api返回的f1,f2有多少

JSON数据

{
 "data":[
 {
   "title": "test",
   "image": "assets/imgs/test.png",
   "date": "22/07/2018 - 19.00",
   "location": "test",
   "details": [
     {
       "f1":[
         {
           "FunctioName": "test",
           "Time": "10:00:00"
         }
       ],
       "f2":[
         {
           "FunctioName": "test",
           "Time": "11:00:00"
         }
       ]
     }
   ]
  }
 ]
}

HTML

<div *ngFor="let item of card">
 <div class="swiper-zoom-container">
  <div class="out-card-box">
   <h2>Date</h2>
   <p>{{item.date}}</p>
   <h2>Program</h2>
   <div *ngFor="let details of item.details; let i = index">
   </div>
  </div>
 </div>
</div>

TS

import { Component } from '@angular/core';
import { App } from 'ionic-angular';
import { DataService } from "../../services/data";
import { LoginPage } from "../login/login";
import { AngularFireAuth } from "angularfire2/auth";
import { Storage } from "@ionic/storage";

@Component({
 selector: 'page-card',
 templateUrl: 'card.html',
})
export class CardPage {

 card:any;
 constructor(private dataservice: DataService, private afAuth:AngularFireAuth, private app:App, private storage:Storage) {

  this.dataservice.cardData().subscribe(
   data => {
    var jsonObj = JSON.parse(data["_body"]);
    this.card = jsonObj.data;
    console.log(jsonObj.data)
  }
 );
}

1 个答案:

答案 0 :(得分:0)

您可以创建一个对象来保存来自api的返回数据,您只需导航对象值。

示例:

export class Class1 {
    data: Class2[];
}

export class Class2 {
    title: string;
    image: string;
    date: string;
    location: string;
    details: Class3[];
}

export class Class3 {
    f1: Class4[];
    f2: Class4[];
}


export class Class4 {
   FunctioName: string;
   Time: string
}


@Component({
 selector: 'page-card',
 templateUrl: 'card.html',
})
export class CardPage {

 card:Class1;
 constructor(private dataservice: DataService, private afAuth:AngularFireAuth, private app:App, private storage:Storage) {

  this.dataservice.cardData().subscribe(
   data => {
    this.card = data;
  }
 );
}

then in your component template

<div *ngFor="let item of card.data">
 <div class="swiper-zoom-container">
  <div class="out-card-box">
   <h2>Date</h2>
   <p>{{item.date}}</p>
   <h2>Program</h2>
   <div *ngFor="let details of item.details; let i = index">
    <!-- Print the remaining items here  -->
   </div>
  </div>
 </div>
</div>