2015-05-29 49 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回調總是執行。