Angular $http service- success(), error(), then() methods



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

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

then 函数返回一个承诺,该承诺由其成功和错误回调的返回值解析。

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的 promise 解析

用户对象或null,因为 success 返回原始$http.get promise。

底线是使用then如果你想做某种类型的承诺链接。

then()方法在成功和失败的情况下都会触发。then()方法接受两个参数,一个成功和一个错误回调,将使用响应对象调用。

相关内容

最新更新