【问题标题】:How to intercept all http requests using AngularJS?如何使用 AngularJS 拦截所有 http 请求?
【发布时间】:2015-01-05 16:17:55
【问题描述】:

我的问题是this question 的更大更广泛的版本。我想拦截 AngularJS 函数内发出的 所有 http 请求。稍后我需要更改请求 URL 并将其传递给服务器..

我该怎么做?到目前为止,我已经使用 $httpProvider 和 $q 创建了一个拦截器,但我只能拦截 $http 请求而不是所有请求,即 如果有人点击我页面上的任何 href 链接等。我的拦截器代码是:-

// register the interceptor as a service
myModule.factory('myHttpInterceptor', function ($q) {
    return {
        // optional method
        'request': function (config) {
            // do something on success
            console.log("request success");
            return config;
        },
        // optional method
        'requestError': function (rejection) {
            // do something on error
            console.log("Request Error");
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        },
        // optional method
        'response': function (response) {
            // do something on success
            console.log("Response received");
            return response;
        },
        // optional method
        'responseError': function (rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
});
myModule.factory('myInterceptor', ['$log', function ($log) {
        $log.debug('$log is here to show you that this is a regular factory with injection');

        var myInterceptor = {
        };

        return myInterceptor;
    }]);
myModule.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('myHttpInterceptor');
}]);

【问题讨论】:

    标签: javascript angularjs angularjs-routing


    【解决方案1】:

    拦截导航到其他页面不同于拦截http请求。也许您想要的是拦截 $location 更改。

    通读一遍。您可以这样做,但这取决于位置更改的位置。

    http://uiadventures.wordpress.com/2013/09/06/routechange-angularjs/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-26
      • 2020-05-04
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2022-09-25
      • 2012-08-11
      相关资源
      最近更新 更多