.success() 和 .then() 之间的 Angular $http 差异 [英] Angular $http difference between .success() and .then()
问题描述
有时我无法使用 $http 服务获取我的数据.而且我并没有 100% 理解 .success() 和 .then() 之间的主要区别
Sometimes I have trouble to fetch my data using $http service. And I did not 100% understand the main difference between .success() and .then()
下面是一个例子,我可以使用 $http().then() 获取数据,但我无法使用 $http().success() 获取我的数据.谁能解释一下原因?
The following is an example that I can fetch the data using $http().then(), but I can't fetch my data using $http().success(). Can anyone explain why?
代码使用 $http.success() http://jsfiddle.net/xoonpLte/11/
Code using $http.success() http://jsfiddle.net/xoonpLte/11/
var manuRep = angular.module('manuRep', ['ui.bootstrap']);
manuRep.controller('MyAppController', function($scope, $http) {
$http.get('https://dl.dropboxusercontent.com/u/59954187/jobs.json').
success(function(response) {
$scope.cats = response.data;
}).
error(function(error){
alert(JSON.stringify(error));
return error;
});
});
代码使用 $http.then() http://jsfiddle.net/xoonpLte/12/
Code using $http.then() http://jsfiddle.net/xoonpLte/12/
var manuRep = angular.module('manuRep', ['ui.bootstrap']);
manuRep.controller('MyAppController', function($scope, $http) {
$http.get('https://dl.dropboxusercontent.com/u/59954187/jobs.json').
then(function(response) {
$scope.cats = response.data;
});
});
推荐答案
.then
is a promise
.then
is a promises
.success
和 .error
是回调.
为什么是回调或承诺?
1.Promise 可以处理全局错误.
2 .Promises 可以被链接(你没有像回调那样的封装)
1 . Promises can handle global errors.
2 . Promises can be chained (you don't have this encapsulation like callbacks)
P = 承诺,
R = 响应,
E = 错误.
P = promise,
R = response,
E = error.
1:
P1(R1)
.P2(R2)
.P3(R3, E3)
如果 promise 1、2 或 3 出现错误,将调用错误 3.
这在回调中是不可能的.
Error 3 will be called if there is an error in promise 1, 2 or 3.
That is not possible with callbacks.
2:
如果你有 3 个承诺:
2:
If you have 3 promises:
P1(R1, E1)
.P2(R2, E2)
.P3(R3,E3)
如果你有 3 个回调
P1().success(P2().success(P3().success().error()).error()).error()
编辑
.service('Auth', function(){
this.isLoggedIn = function(){
return $http.get('url/isLoggedIn');
};
})
.service('getData', function(){
this.name = function(){
return $http.get('url/data/name');
}
})
.controller('MyCTRL', ['Auth', 'getData', function(auth, getData){
Auth.isLoggedIn().then(function(resp){
return getData.name(); //By sending a value back inthe response, next response is called
})
.then(function(res){
//Here we are
}, function(err){
//Global error.
//This will be called in P1 or P2
})
}]);
这篇关于.success() 和 .then() 之间的 Angular $http 差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!