[英]How to wait all data load ajax complete to render page in Anagular?
In my page, I need a page to load a matrix of data (a table), so I make 3 requests to get all data: 在我的页面中,我需要一个页面来加载数据矩阵(一个表),因此我提出3个请求以获取所有数据:
After has all datas, I using a function getRelation(columnIndex, rowIndex)
to get relation data. 在拥有所有数据之后,我使用一个函数
getRelation(columnIndex, rowIndex)
来获取关系数据。
But when rows are loaded before then columns, Angular will try to execute my getRelation
method to render, but it will occur an error because has not column data. 但是,当在行之前插入行时,Angular将尝试执行我的
getRelation
方法进行渲染,但是由于没有列数据,它将发生错误。
Maybe I can just put an if
condition in my function, but I just want know, has some way better to resolve this situation? 也许我可以在函数中添加一个
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
It would be better If you handle rows calculation after colomns. 如果您在列之后进行行计算,那会更好。 Try to use promises in javascript.
尝试在JavaScript中使用Promise。 You can use the library Q.
您可以使用库Q。
https://github.com/kriskowal/q https://github.com/kriskowal/q
As @Vanojx1 sayed, you should use $q
service which is use to combine promises. 正如@ Vanojx1所说,您应该使用
$q
服务,该服务用于组合诺言。 Check the $q documentation for more understanding. 查看$ q文档以了解更多信息。
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.