簡體   English   中英

如何在* ngFor循環之前調用函數? :: Angular2

[英]How to call a function just before the *ngFor loop? ::Angular2

首先,我有一個http請求,看起來像:

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost:8080/getValue/' + v.xid)
    .subscribe(res => {
      this._values.push(res.json());
    }));
};

一切正常,但是問題在於它返回了混亂的,未排序的對象數組。 我想對其進行排序,這就是為什么我做了一個單獨的排序功能:

private sortPoints(){
  this._values.sort((a,b) => a.ts - b.ts);
}

_values變量中的元素由*ngFor循環顯示:

<tr *ngFor="let elem of _values">

每隔5秒調用一次getValues()函數:

this.loadPoints = setInterval(() => {
  this.getValues();
}, 5000);

現在,我必須在某個地方調用排序函數sortPoints() 我認為這樣會很好:

this.loadPoints = setInterval(() => {
  this.getValues();
  this.sortPoints();
}, 5000);

但是不幸的是,它不會影響數組。 *ngFor循環僅用未排序的元素填充表格。 但是,如果我只做一個簡單的按鈕:

<button (click)="sortPoints()">Sort it!</button>

單擊按鈕后立即對數組進行動態排序。

然后我的問題是 ,您是否還有其他想法將函數放置在哪里以使該機制起作用?

任何幫助,高度贊賞。

編輯實現@Sasxa解決方案,收到以下錯誤:

在此處輸入圖片說明

您可以鏈接可觀察的運算符並處理流,因此最后(當您訂閱時)就可以擁有所需的值:

private getValues() {
  this._watchlistElements.map(v =>
    this.http.get('http://localhost:8080/getValue/' + v.xid)
      .map(res => res.json())
      .map(data => this._values.push(data))
      .map(() => this._values.sort((a,b) => a.ts - b.ts))
      .subscribe(sorted => this._values = sorted));
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM