2017-02-18 34 views
0

我有一个带* ngFor的div,它从json加载值。我需要随机加载来自不同json文件的值。 这里div从'mydata'中获取值,下一次我需要从另一个json获取值。我怎样才能做到这一点? 我听说Math.floor((的Math.random()。我怎样在这做什么?或任何其他的方法呢?在离子中随机加载Json文件

html file 
     <div class="row" *ngFor="let data of mydata"> 
     <div class="col">{{data.number}}</div> 
     <div class="col">{{data.code}}</div>   
     </div> 



ts file 

import { Component } from '@angular/core'; 
import { NavController, NavParams } from 'ionic-angular'; 

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

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

} 

// i am providing data here instead of json for development. 
    datas = [ 
{ 
    number: "1", 
    code: "apple", 

}, 
{ 
    number: "2", 
    code: "orange", 

}, 
{ 
    number: "3", 
    code: "banana", 

},{ 
    number: "50", 
    code: "lemon", 

} 

    ]; 

    mydata = this.datas; 

    // i am using this 'mydata' variable in *ngFor to get values 

} 
+0

with angular1我可以做吗? –

+0

IM离子2 – jijishthomas

回答

0

在你的类所创建,指定从中JSON文件你正在阅读并将其分配到DATAS

创建要读取和从你的构造函数初始化它的位置阵列

public locations: Array<string>; 

this.locations = ['firstLocation.json', 'secondLocation.json']; 
let randomJsonFile = this.locations[Math.floor((Math.random() * this.locations.length) + 1)]; 

编辑:。
(OP增加了更详细的问题)

// Outside of the constructor (inside of the class) 

    mydata: Array<Object>; 
    datas0: Array<Object>; 
    datas1: Array<Object>; 
    datas2: Array<Object>; 
    datasCollection: Array<Object>; 

    // Inside of the constructor 

     this.datas0 = [ 
     { number: "1", code: "apple0" }, 
     { number: "2", code: "orange0" }, 
     { number: "3", code: "banana0" }, 
     { number: "50", code: "lemon0" } 
     ]; 

     this.datas1 = [ 
     { number: "1", code: "apple1" }, 
     { number: "2", code: "orange1" }, 
     { number: "3", code: "banana1" }, 
     { number: "50", code: "lemon1" } 
     ]; 

     this.datas2 = [ 
     { number: "1", code: "apple2" }, 
     { number: "2", code: "orange2" }, 
     { number: "3", code: "banana2" }, 
     { number: "50", code: "lemon2" } 
     ]; 

     this.datasCollection.push(this.datas0, this.datas1, this.datas2); 

     this.mydata = this.datasCollection[Math.floor((Math.random() * this.datasCollection.length) + 1)]; 
+0

我新到离子使用andgular 2,所以u能PLS解释代码 我有5个jsons即 one.json,two.json,three.json,four.json&five.json 我需要下面的代码中的jsons的值: mydata = this.datas; 我在这个'mydata'中使用 * ngFor =“let data of mydata”> – jijishthomas

+0

请更新您的第一个问题,提供更详细的问题并添加您的课程的代码示例。 –

+0

我已更新问题 – jijishthomas