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

查看:127
本文介绍了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需要看看在code,如果有什么不对然后用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.

有没有办法,我可以因此每次一个$ HTTP调用时AngularJS内自动完成这一然后它再检查这一点,只返回数据变量内容的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?

推荐答案

您可以通过角添加一个拦截器 $ httpProvider.interceptors 拦截响应1.1.4+(看到文档这里搜索拦截器)。

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 ,将得到传递给你的控制器code,以及在这里:

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 是德$ P $与角1.1.4 pcated ):


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

也许有更好的方式,但我认为你可以做同样的事情到<一个href=\"http://stackoverflow.com/questions/11786764/track-to-see-when-a-view-changes-in-angularjs\">this帖子使用HTTP响应拦截器(形容这里)(针对特定内容类型像JSON)在这里你可能会拒绝更改或抛出,即使调用是成功的一个例外。您可以修改 response.data ,将得到传递给你的控制器code,以及在这里。

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天全站免登陆