如何在angular js中从HTTP拦截器$ httpProvider读取URL和参数

时间:2018-09-04 17:24:36

标签: angularjs angular-http-interceptors

在这里我可以从HttpIntercepter获取URL字符串和POST请求的参数,并将该信息推送到IndexedDB。但是我不知道如何从httpintercepter获取URL和参数。

angular.module("app").config(['$httpProvider', function ($httpProvider) {
        if (!$httpProvider.defaults.headers.get) {
            debugger;
            $httpProvider.defaults.headers.get = {};
            console.log('POST method triggered');
        }
        else {
        }
        $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
    }]);

发帖是针对托管在不同服务器中的API

  var tfscapacity = 'https://server.com/folderName/Folder/folderService/folderService.svc/GetResourceCapacityPlan';
        var params = {
            teamsite: 'team',
            project: 'pjt',
            iterationId: 'Sprint-3',
            team: 'team',
            username: 'UserName',
            password: 'PassWord'
        };

        $http.post(tfscapacity, params, null).then(function (response) {
        });  

1 个答案:

答案 0 :(得分:0)

经过几次搜索,我找到了答案。您必须编写一个过滤器并将其注入到http

$httpProvider.interceptors.push('myHttpInterceptor');

请找到完整的代码

angular.module("app").config(['$httpProvider', function ($httpProvider) {
        if (!$httpProvider.defaults.headers.get) {
            $httpProvider.defaults.headers.get = {};
            $httpProvider.interceptors.push('myHttpInterceptor');
        }
        else {
        }
        $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
        $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
        $httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
    }
]);

angular.module('app').factory('myHttpInterceptor', function ($q) {
    return {
        // optional method
        'request': function (config) {
            debugger;
            return config;
        },
        // optional method
        'requestError': function (rejection) {
            // do something on error
            return $q.reject(rejection);
        },
        // optional method
        'response': function (response) {
            // do something on success
            return response;
        },
        // optional method
        'responseError': function (rejection) {
            // do something on error
            return $q.reject(rejection);
        }
    };
});