【发布时间】:2015-02-01 23:03:56
【问题描述】:
什么时候应该使用then() 方法,then(), success(), error() 方法有什么区别?
【问题讨论】:
标签: angularjs
什么时候应该使用then() 方法,then(), success(), error() 方法有什么区别?
【问题讨论】:
标签: angularjs
除了成功将响应解包到回调中的四个属性之外,then 没有。两者有细微差别。
then 函数返回一个由成功和错误回调的返回值解析的承诺。
success 和 error 也返回一个 promise,但它总是通过 $http 调用本身的返回数据来解决。这是角度源中success 的实现方式如下:
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
要了解它如何影响我们的实现,请考虑一个示例,我们根据电子邮件 ID 检索用户是否存在。下面的 http 实现尝试根据 userid 检索用户。
$scope.userExists= $http.get('/users?email='test@abc.com'')
.then(function(response) {
if(response.data) return true; //data is the data returned from server
else return false;
});
分配给userExists 的承诺解析为真或假;
而如果我们使用success
$scope.userExists= $http.get('/users?email='test@abc.com'')
.success(function(data) { //data is the response user data from server.
if(data) return true; // These statements have no affect.
else return false;
});
分配给userExists 的承诺解析用户对象或null,因为success 返回原始的$http.get 承诺。
如果你想做某种类型的承诺链,最重要的是使用then。
【讨论】:
then() 方法在成功和失败的情况下都会触发。 then() 方法接受两个参数,一个成功回调和一个错误回调,将使用响应对象调用。
【讨论】: