Get random object from local json


#1

I try to get a random object from a local Json file in my Ionic3 App.

When I click a button, I would like to get a random object from my json file and display specific datas from this object.
Currently, I can get a random object but I don’t know to display its data in the view.
This is a dummy project and I am not sure what’s the appropriate way to do this.

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"
    }
  ]
}

#2

first off i prefer using data store inside an object you can import (if your not getting the data from external)

i created a “data” folder and added

cards.ts

export default
  {
    "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"
      }
    ]
  };

then in my “Models” folder i created

cards.interface.ts

export interface Card {
  id: string;
  question: string;
  answer: string;
  hint: string;
}

then i generated a page

ionic g page random-cards

and added it to app.modules. of course

random-cards.ts

import {Component, OnInit} from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import cards from '../../data/cards';
import {Card} from "../../Models/cards.interface";

/**
 * Generated class for the RandomCardsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-random-cards',
  templateUrl: 'random-cards.html',
})
export class RandomCardsPage implements OnInit {
  cards: Card[];
  randomCard: Card[];


  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ngOnInit() {
    this.cards = cards.cards;
  }


  ionViewDidLoad() {
    console.log('ionViewDidLoad RandomCardsPage');
    console.log(this.cards);
  }

  getRandom() {
    let rd = Math.floor(Math.random() * this.cards.length);
    this.randomCard = [this.cards[rd]];
  }

}

then

random-cards.html

<!--
  Generated template for the RandomCardsPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>random-cards</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-list>
          <ion-item *ngFor="let card of cards">
            ({{card.id}}) {{card.question}} - {{card.answer}}

          </ion-item>
        </ion-list>

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>

        <button ion-button (click)="getRandom()">Get Random</button>

      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <ion-list>
          <ion-item *ngFor="let rc of randomCard">
            ({{rc.id}}) {{rc.question}} - {{rc.answer}}
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-content>


#3

Thanks it works great ! But can you explain why do you prefer using data store in an object instead of a json file ?


#4

if it is a static file, doing it this way i don’t have to invoke the http and map, it is already an Object