2013-06-19 44 views
10

如何確保complete()函數將運行,無論$ http調用的結果使用與Angular.js提供的promise API?

$http({ 
    method: 'POST', 
    url: submitUrl, 
    data: $scope.data 
}) 
.success(function(data) { 
     // execute this code on success 
}) 
.error(function(data) { 
     // execute this code on error 
}) 
.complete(function() { 
    // execute this code regardless of outcome 
}); 

一旦請求完成,就可以使用它來隱藏AJAX微調器圖標。無論請求結果如何,您都希望隱藏微調器。

+0

你想通過這種方式達到什麼目的? –

回答

15

我不是世界上在Angular.js最大的專家,但明白,你可以做如下:

whatever.then(function() { 
    // success code here 
}, function() { 
    // error code here 
    return true; // return anything that's not undefined (and not a `throw()`) to force the chain down the success path at the following then(). 
}).then(function() { 
    // "complete" code here 
}); 

你基本上是被迫從一個或多個.then(),這是一個$ Q承諾的圖謀什麼唯一的方法。

+0

有道理。第二個.then()在第一個被解析或拒絕後執行。 – Failpunk

8

如果你不在乎,如果該請求是成功還是失敗,那麼你可以通過同樣的回調successerror ...

var cb = function(response){ 
     // do something 
    }; 


    $http.post(submitUrl, $scope.data).success(cb).error(cb); 

    // OR 

    $http.post(submitUrl, $scope.data).then(cb, cb); 

但要知道,successerror回調有不同簽名比then回調。

此外,承諾通過在角模板引擎,這意味着在模板中,你可以把連接到一個範圍的承諾認定爲如果他們是最終的價值觀。

這意味着,你可以這樣做:

控制器:

$scope.article = $http.get('/articles/' + articleId); 

模板:

<article ng-cloak> 
    <h3>{{article.title}}</h3> 
    <div>{{article.content}}</div> 
</article> 

而當$http.get承諾已經解決了就會更新。

+1

我會閱讀承諾和模板引擎,聽起來很有趣。 – Failpunk

+0

大約1年後,快速注意到模板中的承諾(自動)解包已在[版本1.2.0中刪除](https://github.com/angular/angular.js/commit/fa6e411da26824a5bae55f37ce7dbb859653276d)。 – bernhardw

12

這取決於你想要做什麼,但對於清理邏輯和類似的,你也可以使用finally()要麼就履行或拒絕你的諾言的運行:

promise.finally(function() { 
    // Do something regardless of outcome. 
}); 

請注意,雖然finally()$q(和一些其他庫)支持不是official draft的一部分。

+0

這個工作對我來說,我用來控制請求ajax完成並隱藏圖標加載 – vandersondf