paq*_*ttg 2 angularjs restangular
我们使用REST API,其中一个功能允许用户对对象进行批量编辑,每个对象都需要PUT请求来编辑所述对象.现在我们做
angular.foreach(objects, function(data) {
restangular.one('user', user.id).one(object).put();
});
angular.updateInfo('user');
Run Code Online (Sandbox Code Playgroud)
这里的问题是updateInfo调用与PUT调用异步发生,因此新的用户信息并不总是完整/正确.有没有可能有类似的东西.
var promise = restangular.one('user', user.id);
angular.foreach(objects, function(data) {
promise.one(object).put();
});
promise.then(function (data) {
angular.updateInfo('user');
});
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
是的,你可以做到这一点,但它并不像你写的那么容易
我假设每个人put都会给你一个承诺(我从未使用过restangular).你想要做的是创建一个承诺列表,然后使用$q.all.
注意一定要注入$q您的控制器/服务.
// Initialise an array.
var promises = [];
angular.foreach(objects, function(data) {
// Add the `put` to the array of promises we need to complete.
promises.push(restangular.one('user', user.id).one(object).put());
});
// combine all the promises into one single one that resolves when
// they are all complete:
$q.all(promises)
// When all are complete:
.then( function(resultArray){
// An array of results from the promises is passed
var resultFromFirstPromise = resultArray[0];
// Do whatever you want here.
angular.updateInfo('user');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1648 次 |
| 最近记录: |