AngularJS: need to fire event every time an ajax call is started

后端 未结 4 1648
我在风中等你
我在风中等你 2020-12-13 10:33

I am trying to fire an event on $rootScope every time an ajax call is started.

var App = angular.module(\'MyApp\');

App.config(function ($httpProvider) {
           


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 11:23

    Cagatay is right. Better use $http interceptors:

    app.config(function ($httpProvider, $provide) {
        $provide.factory('httpInterceptor', function ($q, $rootScope) {
            return {
                'request': function (config) {
                    // intercept and change config: e.g. change the URL
                    // config.url += '?nocache=' + (new Date()).getTime();
                    // broadcasting 'httpRequest' event
                    $rootScope.$broadcast('httpRequest', config);
                    return config || $q.when(config);
                },
                'response': function (response) {
                    // we can intercept and change response here...
                    // broadcasting 'httpResponse' event
                    $rootScope.$broadcast('httpResponse', response);
                    return response || $q.when(response);
                },
                'requestError': function (rejection) {
                    // broadcasting 'httpRequestError' event
                    $rootScope.$broadcast('httpRequestError', rejection);
                    return $q.reject(rejection);
                },
                'responseError': function (rejection) {
                    // broadcasting 'httpResponseError' event
                    $rootScope.$broadcast('httpResponseError', rejection);
                    return $q.reject(rejection);
                }
            };
        });
        $httpProvider.interceptors.push('httpInterceptor');
    });
    

    I think interceptors works for versions after 1.1.x. There was responseInterceptors before that version.

提交回复
热议问题