Angular $ http service- success(),error(),then()方法

时间:2014-12-04 06:35:04

标签: angularjs

我应该何时使用then()方法,then(), success(), error()方法之间有什么区别?

2 个答案:

答案 0 :(得分:2)

除了成功之外,将响应解包为回调中的四个属性,而then则没有。两者之间存在细微差别。

then函数返回一个promise,该promise通过其成功和错误回调的返回值来解析。

successerror也会返回一个承诺,但始终使用$http调用本身的返回数据来解析。这就是角度源中success的实现方式:

  promise.success = function(fn) {
    promise.then(function(response) {
      fn(response.data, response.status, response.headers, config);
    });
    return promise;
  };

要了解它如何影响我们的实现,请考虑一个示例,我们根据电子邮件ID检索用户是否存在。下面的http实现尝试根据用户ID检索用户。

$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

答案 1 :(得分:1)

成功和失败案例都会触发

then()方法。 then()方法成功获取两个参数,并使用响应对象调用错误回调。