2015-05-29 51 views
0

这可能是一个没有意义的问题,但我仍然无法把握自己的承诺,特别是如何编写代码。 (我已阅读过几篇文章,但其中大部分都是抽象的,而我只是没有写足够清晰的图片) 我有一个AngujlarJS应用程序,通过http请求获取数据到另一个服务器,第一。我已经能够从promise中检索响应并在我的应用中使用它。但是,因为我的代码写得不好。它在承诺解决导致问题之前执行其他代码。它在有数据之前开始加载页面。AngularJS如何在解决承诺后才执行代码? (with Restangular)

我有什么是:

var userTotals = *http request which returns a promise 

$scope.data = userTotals.$object 

//code that does someting with $scope.data 

我需要的是(我认为)

var userTotals = *http request which returns a promise 

$scope.data = userTotals.$object. 
    beforethisresolves(function{ 
    show fancy loading icon or something }) 
    .whenthis resolves(function{ 
    //code that does someting with $scope.data 
    } 

但我不能得到正确的语法。

+0

http请求退回'promise',你有'then' https://docs.angularjs.org/api/ng/service/$http –

回答

2

这是它看起来像一般:

var promise = $http.post('/url'); 

console.log('Request started'); 

promise.then(function(result) { 
    console.log('Success'); 
    console.log(result); 
}, function() { 
    console.log('Failure'); 
}); 

事实上,$q AngularJS documentation帮了我一个很好的协议,以让我的头周围承诺概念。

希望这会有所帮助!

+0

谢谢,这正是我所需要的。生病请检查文档。 – Mischa

0
var successCallback = function(){//...}; 
var errorCallback = function(){//...}; 

$http 
.post('url', data) 
.success(successCallback) 
.error(errorCallback); 

//OR 

$http 
.post('url', data) 
.then(successCallback, errorCallback); 
0

假设你使用的引导模态,你可以做到以下几点:

function openModalWithProgressIndicator(deferred) { 
    const progressModal = $uibModal.open({ 
    templateUrl: 'templates/modals/progress.html', 
    backdrop: 'static' 
    }); 
    return deferred.then(function (value) { 
    return value; 
    }).finally(function() { 
    progressModal.close(); 
    }); 
} 

deferred参数传递给这个函数是一个承诺。这就是说,你现在可以做到以下几点:

const deferred = $http.post('http://somewhere/data', {foo: 'bar'}); 

openModalWithProgressIndicator(deferred) 
    .then(function (httpResponse) { 
    // do sth with httpResponse.data 
    }).catch(function (error) { 
    // do sth with error 
    }); 

所以要注意点主要是finally回调总是执行。