2016-10-10 101 views
0

在我的網頁,我需要一個頁面加載數據的矩陣(表),所以我讓3次請求獲得的所有數據:如何等待所有數據加載ajax完成呈現Anagular中的頁面?

  • 列數據
  • 行數據
  • 關係數據

有了所有數據後,我使用函數getRelation(columnIndex, rowIndex)來獲取關係數據。

但是,當行加載之前,然後列,Angular會嘗試執行我的getRelation方法來呈現,但它會發生錯誤,因爲沒有列數據。

也許我可以在我的函數中放一個if條件,但我只想知道,有更好的方法來解決這種情況嗎?

this.relations = []; 
this.columns = []; 
this.rows = []; 
this.getRalation = function getRalation(columnIndex, rowIndex) { 
    var column= this.columns[columnIndex]; 
    var row= this.rows[rowIndex] 

    var relation = $myService.getSomthing(this.relations, column.ID, row.ID); 

    return relation; 
}.bind(this); 

$http.post(url, {}).then(function(res) { 
    this.rows = res.data; 
}.bind(this)); 

// same code for columns and relations 
+0

使用NG-顯示或NG-如果 –

+0

你能告訴你使用,讓您的請求 – Merlin

+0

@Lorenzo我更新我的帖子的代碼,把一個請求示例 – Lai32290

回答

1

使用$q服務:

$q.all([/*promise from row request*/,/*promise from column request*/]).then(function(result){ 
    var rows = result[0]; 
    var columns = result[1]; 
    //parse row and cols, use getRalation here 

}); 
0

正如@ Vanojx1賽義德,你應該使用$q服務,這是利用諾言結合起來。請查看$q documentation瞭解更多。

var rows = $http.post(url, {}).then(function(res) { 
    return res.data; 
}) 


var columns = $http.post(url, {}).then(function(res) { 
    return res.data; 
}) 

var relationship = $http.post(url, {}).then(function(res) { 
    return res.data; 
}) 


var results = []; 

$q.all([rows, columns, relationship]).then(function(result){ 
    for (var i = 0; i < result.length; i++){ 
     results.push(result[i]); 
    } 
    result[0] //rows data 
    result[1] //columns data 
    result[2] //relationship data 

}); 
相關問題