【问题标题】:Load Json files randomly in ionic在 ionic 中随机加载 Json 文件
【发布时间】:2017-02-18 10:46:19
【问题描述】:

我有一个带有 *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

 }

【问题讨论】:

  • 用angular1可以吗?
  • 我在 ionic 2 中使用了 andgular 2

标签: javascript angularjs json ionic-framework


【解决方案1】:

在您创建的类中,您指定了从哪个 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)];

【讨论】:

  • 我是 ionic 新手,所以你能解释一下我有 5 个 json 的代码,即 one.json、two.json、three.json、four.json 和 Five.json 我需要来自以下代码中的 json:mydata = this.datas;我在 *ngFor="let data of mydata"> 中使用这个'mydata'
  • 请用更详细的问题更新您的初始问题,并添加您班级的代码示例。
  • 感谢代码,它可以工作,但现在我收到错误 Runtime Error Error in ./ShowallPage class ShowallPage - 原因:无法读取未定义的属性“代码”,
猜你喜欢
  • 2015-11-14
  • 2018-08-23
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2017-10-29
  • 2021-02-27
相关资源
最近更新 更多