且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS 拦截所有 $http JSON 响应

更新时间:2022-04-12 22:16:01

您可以使用 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');
});