AngularJS拦截器

时间:2016-02-02 09:50:59

标签: angularjs

我想捕获从我的单页应用程序发出的所有请求,例如单击不同的选项卡或任何超链接。

我编写了一个拦截器,想要为所有请求添加一个ajax调用。

.factory('httpRequestInterceptor', function($q,$http){
    return {
        request: function($http,config){
            window.alert(config.url);               
            var dummyValue = $http.get("url");
            return config;      
        }                       
    }
})
.config(function($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找http logger类的工厂。你可以使用这个

.config(function ($provide, $httpProvider) {

    // Intercept http calls.
    $provide.factory('MyHttpInterceptor', function ($q) {
        return {
            // On request success
            request: function (config) {
                console.log(config); // Contains the data about the request before it is sent.

                // Return the config or wrap it in a promise if blank.
                return config || $q.when(config);
            },

            // On request failure
            requestError: function (rejection) {
                console.log(rejection); // Contains the data about the error on the request.

                // Return the promise rejection.
                return $q.reject(rejection);
            },

            // On response success
            response: function (response) {
                console.log(response); // Contains the data from the response.

                // Return the response or promise.
                return response || $q.when(response);
            },

            // On response failture
            responseError: function (rejection) {
                console.log(rejection); // Contains the data about the error.

                // Return the promise rejection.
                return $q.reject(rejection);
            }
        };
    });

    // Add the interceptor to the $httpProvider.
    $httpProvider.interceptors.push('MyHttpInterceptor');

});

我测试过,它也适用于routeProvider导航。有关详细信息,请查看此博客https://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/