AngularJS 拦截所有 $http JSON 响应 [英] AngularJS Intercept all $http JSON responses

查看:28
本文介绍了AngularJS 拦截所有 $http JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

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.

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

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?

推荐答案

您可以使用 Angular 1.1.4+ 向 $httpProvider.interceptors 添加拦截器来拦截响应(请参阅文档 此处 搜索拦截器.

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

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

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.data that will get passed to your controller code as well here:

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');
});

<小时>

注意:以下是 1.1.4 之前版本的原始答案(responseInterceptors 在 Angular 1.1.4 中已弃用):


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

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

Maybe there's a better way but I think you can do something similar to this post with 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.data that will get passed to your controller code as well here.

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');
});

这篇关于AngularJS 拦截所有 $http JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆