0

我想创建一个简单的模式,我想在其中输出一系列多个 ajax 请求的结果。

脚本应该这样做:单击按钮后,打开模式,发出 ajax 请求,在模式中显示请求的输出,发出另一个 ajax 请求,更新模式消息并继续......

我曾尝试使用提出 ajax 请求的服务,但不确定这是否是最佳解决方案......

这是一个plunker:http ://plnkr.co/edit/JySrMYocYGtCvftHLw4G?p=preview

4

1 回答 1

0

据我所知,您只能使用serviceto call $httpthat should return promisethen回调应该实现到控制器中,而不是service像您实现的那样。

就像是:

myModule.factory('ajax_post', ['$http',  function(_http) {   

var path = 'src/php/data.ajax.php';

return{
    init: function(jsonData){
        var _promise= _http.post(path, 
            jsonData
            ,{
                headers: {
                    'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'
                }
            }
            );            
        return _promise; 
    } 
  }   
}]);

现在你可以调用控制器:

ajax_post.init(jsonData);

你在控制器中的承诺“链”应该是:

var promise = asyncFunction(parameters);

promise.then(function (result) {
  return otherAsyncFunction(result * 2);
}).then(function(result) {

if (result < 0) { throw "Some Error" };
  return mayBeSyncOrAsyncFunction(result);
}).then(function(result) {
  console.log("Final Result: " + result);
}, function(error) {
// Handle error (exception, etc).
});

另一个好方法是使用$q

如果你想等待多个承诺

$q.all([promise, …])新承诺

newPromise将在所有给定的 Promise 都解决后解决如果任何给定的 Promise 被拒绝,newPromise也将被拒绝

于 2013-06-01T09:21:53.553 回答