2017-05-16 119 views
0

我要顯示在div element引號這樣,我想更新報價每5分鐘或東西之間的隨機洗牌。但是,當我在html中創建一個*ngFor時,它將顯示數組的所有元素。有沒有辦法每隔5分鐘在陣列中顯示隨機選取的報價?離子2 - * ngFor值

這裏是我的TS文件,我創建數組:

public quotesArray: any[] = []; 

    constructor(public navCtrl: NavController) { 
    this.quotesArray.push('testQuote'); 
    this.quotesArray.push('testQuote2'); 
    this.quotesArray.push('testQuote3'); 
    this.quotesArray.push('testQuote4'); 
    } 

這裏是HTML:

<div *ngFor="let q of quotesArray; let i = index">{{ q }}</div> 

我怎樣才能選擇一個隨機的報價每5分鐘?

+0

假設你的報價從服務器你爲什麼不只是做一個HTTP請求,每5分鐘爲一個新的報價來嗎? –

+0

他們現在不是來自服務器。 – Sreinieren

回答

2

這就是*ngFor做,通過迭代和數組並打印在其內部產生的HTML的次數作爲數組的長度在屏幕上。

如果你想在同一時間只顯示一個單引號和更新它每5分鐘就可以使用setInterval()方法來操縱報價。

public quotesArray: any[] = []; 
public randomQuote: string; 

constructor(public navCtrl: NavController) { 
    this.quotesArray.push('testQuote'); 
    this.quotesArray.push('testQuote2'); 
    this.quotesArray.push('testQuote3'); 
    this.quotesArray.push('testQuote4'); 

    // immediately show one random quote; 
    this.quotesArray[Math.floor(Math.random() * this.quotesArray.length)]; 

    setInterval(() => { 
    this.randomQuote = this.quotesArray[Math.floor(Math.random() * this.quotesArray.length)]; // this'll get the quote depending on your array length 
    }, 300000); // needs to be in milliseconds 
} 

而在你的HTML你必須

<div>{{randomQuote}}</div> 

丹尼爾·庫克的評論,如果報價來自服務器,你可以把它每隔5分鐘,只需要實現內部的代碼的setInterval。

希望這有助於:d

+0

但是這不會顯示中間值,只顯示5分鐘後的值。因此,價值具有顯示和超過5分鐘 – Sreinieren

+0

編輯答案後的變化,只是立即給報價爲變量 –