本文介绍了角$ HTTP服务 - 成功(),错误(),则()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我应该使用则()方法是什么之间的差异则(),成功(),错误()的方法呢?

When should I use then() method and what is the difference between then(), success(), error() methods ?

推荐答案

除了成功未包装的响应进入回调,其中四个属性为然后不。有两者之间微妙的差异。

Other than the success un-wraps the response into four properties in callback, where as then does not. There is subtle difference between the two.

然后函数返回的返回值决定了它的成功和错误回调的承诺。

The then function returns a promise that is resolved by the return values for it's success and error callbacks.

成功错误太返回的希望,但是它总是与返回的数据解析 $ HTTP 调用自身。这是在角度源成功实施的样子:

The success and error too return a promise but it is always resolved with the return data of $http call itself. This is how the implementation for success in angular source looks like:

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

要了解它如何影响我们的实现,考虑我们检索用户是否存在基于电子邮件ID的例子。下面的HTTP实现尝试检索基于用户ID用户。

To understand how it can affect our implementation, consider an example where we retrieve whether user exists based on email id. The http implementation below tries to retrieve the user based on userid.

$scope.userExists= $http.get('/users?email='[email protected]'')
                        .then(function(response) {
                            if(response.data) return true;  //data is the data returned from server
                            else return false;
                         });

分配到 userExists 的承诺解析为true或false;

The promise assigned to userExists resolves to either true or false;

然而,如果我们使用成功

$scope.userExists= $http.get('/users?email='[email protected]'')
                        .success(function(data) {    //data is the response user data from server.
                            if(data) return true;  // These statements have no affect.
                            else return false;
                         });

分配到 userExists 的承诺解决或者用户对象或,因为成功返回原始的 $ http.get 的承诺。

The promise assigned to userExists resolves either a user object or null, because success returns the original $http.get promise.

底线是使用然后如果你想要做某种类型的诺言链的。

Bottom line is use then if you want to do some type of promise chaining.

这篇关于角$ HTTP服务 - 成功(),错误(),则()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 12:11