AngularJS 拦截所有 $http JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11956827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:29:36  来源:igfitidea点击:

AngularJS Intercept all $http JSON responses

jsonangularjsinterceptor

提问by matsko

I have an application built using AngularJS and a server-side backend that delivers all requests in JSON form. Each and every request is wrapped in a JSON container that contains a data variable which contains the data specific to the request. The other data, which are used to keep state and control within the application, check for errors and success messages, and check for session flags. All of these other variables are served with EVERY request and are examined first before the data variable is.

我有一个使用 AngularJS 构建的应用程序和一个以 JSON 形式提供所有请求的服务器端后端。每个请求都包装在一个 JSON 容器中,该容器包含一个数据变量,该变量包含特定于请求的数据。其他数据用于在应用程序中保持状态和控制,检查错误和成功消息,并检查会话标志。所有这些其他变量都随每个请求一起提供,并在数据变量之前首先检查。

Right now I have a method to examine the contents of the JSON response first and then the data itself.

现在我有一种方法可以先检查 JSON 响应的内容,然后再检查数据本身。

$http.get('something.json').success(function(response) {
   var data = examineJSONResponse(response);
   //do the data stuff
});

This works and the examineJSONResponse takes a look at the code and if there is something wrong then it throws an exception and reloads the page using window.location.href.

这是有效的,且examineJSONResponse 会查看代码,如果有问题,则会抛出异常并使用window.location.href 重新加载页面。

Is there any way that I can automate this within AngularJS so that each time a $http call is made then it checks this and ONLY returns the data variable contents as the JSON response?

有什么方法可以在 AngularJS 中自动执行此操作,以便每次进行 $http 调用时,它都会检查这一点,并且仅将数据变量内容作为 JSON 响应返回?

回答by Gloopy

You can intercept responses by adding an interceptor to $httpProvider.interceptorswith Angular 1.1.4+ (see documentation heresearch for interceptors).

您可以通过向$httpProvider.interceptorsAngular 1.1.4+添加拦截器来拦截响应(请参阅此处的文档搜索拦截器)。

For a specific content type like json you can potentially reject changes or throw an exception even if the call was a success. You can modify the response.datathat will get passed to your controller code as well here:

对于像 json 这样的特定内容类型,即使调用成功,您也可能拒绝更改或抛出异常。您也可以在response.data此处修改将传递给您的控制器代码的 :

myModule.factory('myHttpInterceptor', function ($q) {
    return {
        response: function (response) {
            // do something on success
            if(response.headers()['content-type'] === "application/json; charset=utf-8"){
                // Validate response, if not ok reject
                var data = examineJSONResponse(response); // assumes this function is available

                if(!data)
                    return $q.reject(response);
            }
            return response;
        },
        responseError: function (response) {
            // do something on error
            return $q.reject(response);
        }
    };
});
myModule.config(function ($httpProvider) {
    $httpProvider.interceptors.push('myHttpInterceptor');
});


NOTE:Here is the original answer for versions prior to 1.1.4 (responseInterceptorswere deprecated with Angular 1.1.4):

注意:这是 1.1.4 之前版本的原始答案(responseInterceptors已被 Angular 1.1.4 弃用):

Maybe there's a better way but I think you can do something similar to this postwith the http response interceptor (described here) (for a specific content type like json) where you potentially reject changes or throw an exception even though the call was a success. You can modify the response.datathat will get passed to your controller code as well here.

也许有更好的方法,但我认为您可以使用 http 响应拦截器(此处描述)(针对特定的内容类型,如 json)执行类似于这篇文章的操作,即使调用成功,您也可能拒绝更改或抛出异常. 您也可以在此处修改将传递给您的控制器代码的 。response.data

myModule.factory('myHttpInterceptor', function ($q) {
    return function (promise) {
        return promise.then(function (response) {
            // do something on success
            if(response.headers()['content-type'] === "application/json; charset=utf-8"){
                // Validate response if not ok reject
                var data = examineJSONResponse(response); // assumes this function is available

                if(!data)
                    return $q.reject(response);
            }
            return response;
        }, function (response) {
            // do something on error
            return $q.reject(response);
        });
    };
});
myModule.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');
});

回答by matsko

Another solution is to create a service and use that around the $http variable.

另一种解决方案是创建一个服务并在 $http 变量周围使用它。

angular.module('App', [])
  .factory('myHttp',['$http',function($http) {
    return function(url, success, failure) {
      $http.get(url).success(function(json) {
          var data = examineJSONResponse(json);
          data && data.success ? success() : failure();
        }).error(failure);
      );
    }
}]);

And now this can be called like:

现在可以这样调用:

myHttp(url, onSuccess, onFailure);