在 AngularJS 中,如何对“$http”的所有响应应用检查函数

In AngularJS, how can I apply a check function on all the responses of `$http`?

本文关键字:响应 函数 检查 应用 http AngularJS      更新时间:2023-09-26
$http({
    method: 'POST',
    url: '/getAllUsers'
}).success(function(data, status, headers, config) {
    if (data.length === 0) {
        $location.path('/admin/login');
    }
    // process data
    if (data.ok == 1) {
        // correct data
    } else {
        // error
    }
})

我使用 $http 来获取服务器数据,如果身份验证失败,服务器将响应一个空字符串。我想做的是,如果data为空,那么应用程序应该重定向到登录页面。但是由于有很多控制器,并且每个控制器都有多个$http调用,所以我不想到处复制和粘贴定向代码。

有什么方法可以在每个$http响应上"注入"此函数,而无需在任何地方编写相同的代码?

我是否只能在某些特定控制器中的$http调用上应用它?

您可以使用 http 中间器。在收到来自后端的响应后,立即调用$http交互器的响应方法。您可以修改响应或执行其他操作。该方法使用 http 响应对象调用,需要直接返回响应对象,或者作为包含响应或新响应对象的承诺返回。

$provide.factory('myHttpInterceptor', function() {
  return {
    'response': function(response) {
       if (/* response failed */ ) {
          // $rootScope broadcast
          // or $location login
          // or whatever you want
       }
       return response;
     }
   };
});
$httpProvider.interceptors.push('myHttpInterceptor');

编辑:我不确定这是否是$http配置的正确用法(我从来没有这样做过..),但您也可以有条件地将transformResponse函数添加到单个$http调用中,如下所示:

function transformErrorResponse(data, headersGetter, status) {
  if (/* failed */)
    // handle failure
}
$http({ transformResponse : transformErrorResponse})
  .get(/*  */)
  .then(/*  */);

您可以创建一个factory定义并将其作为Interceptor推送到config phase中(使用 $httpprovider

工厂定义

angular.module('myApp').factory('httpInterceptor', ['$location', function($location) {
    var httpInterceptor = {
        response: function(config){ 
            if (config.data.trim() == "") {
                $location.path(''login');
            }
            return config;
        }
    };
    return httpInterceptor;
}]);

配置阶段

angular.module('myApp').config(['$httpProvider' ,function($httpProvider) {
   $httpProvider.interceptors.push('httpInterceptor');
}]);
您可以在

模块配置中为$http编写一个简单的配置,并在$http配置的 transformResponse 属性中编写错误处理。像这样:

angular.module("yourModule", []).config ($http) ->
     $http({
        transformResponse:(data, headersGetter, status)->
             /**Handle your data empty stuff here. ***/
      })