从json ionic 3显示对象的值

时间:2017-12-05 14:34:31

标签: json angular random ionic3

我尝试从Ionic3应用程序中的本地Json文件中获取随机对象。

而不是显示所有"问题","答案"和#34;提示"从我的"卡",我只想显示随机选择的卡的值。

这是一个虚拟项目,我不确定这是做什么的恰当方法。

home.ts

  cards: any;

  getLocalData() {
    this.http.get('assets/data/cards.json').map(res => res.json()).subscribe(res => {
        this.cards = res.cards;
        this.cards.rd = this.cards[Math.floor(Math.random() * this.cards.length)];
        console.log(this.cards.rd);
    },
     (err) => {
      alert("failed loading json data");
    })
  }

home.html的

 <button ion-button round (click)="getLocalData()">Charger</button>

    <ion-list>
      <ion-item *ngFor="let card of cards">
        <h2>{{card.question}}</h2>
        <h2>{{card.answer}}</h2>
        <h2>{{card.hint}}</h2>
      </ion-item>
    </ion-list> 

cards.json

{
  "cards": [
    {
      "id": "1", 
      "question": "question 1",
      "answer": "reponse 1",
      "hint": "hint 1"
    },
    {
      "id": "2",
      "question": "question 2",
      "answer": "reponse 2",
      "hint": "hint 2"
    },
    {
      "id": "3",
      "question": "question 3",
      "answer": "reponse 3",
      "hint": "hint 3"
    }
  ]
}

0 个答案:

没有答案