我有一个带* ngFor的div,它从json加载值。我需要随机加载来自不同json文件的值。 这里div从'mydata'获得价值,下次我需要从另一个json获取值。我怎样才能做到这一点? 我听说过Math.floor((Math.random()。我该怎么做?或者其他任何方法?
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 :(得分:0)
在您创建的类中,您指定了正在读取的JSON文件并将其分配给数据。
创建一个您想要读取的位置数组,并从构造函数中初始化它。
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)];