AngularJS:需要每一个Ajax调用启动时开火事件 [英] AngularJS: need to fire event every time an ajax call is started

查看:153
本文介绍了AngularJS:需要每一个Ajax调用启动时开火事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每一个Ajax调用启动时的$ rootScope触发事件。

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) {
    //add a transformRequest to preprocess request
    $httpProvider.defaults.transformRequest.push(function () {
        //resolving $rootScope manually since it's not possible to resolve instances in config blocks
        var $rootScope = angular.injector(['ng']).get('$rootScope');
        $rootScope.$broadcast('httpCallStarted');

       var $log = angular.injector(['ng']).get('$log');
       $log.log('httpCallStarted');
    });
});

事件httpCallStarted它没有被解雇。我怀疑这是不正确的使用$ rootScope或配置块任何其他实例服务。如果是这样,我怎么能得到一个事件每次HTTP调用开始,而不必通过一个配置对象每次我想提出一个通话时间?

The event 'httpCallStarted' it's not being fired. I suspect that it's not correct to use $rootScope or any other instance service in config blocks. If so, how can I get an event everytime an http call is starting, without having to pass a config object in every time I am making a call?

在此先感谢

推荐答案

您总是可以在一个服务包$ HTTP。由于服务只设置一个时间,你可以只是服务工厂设立的事件为您服务。感觉有点hackish的给我,说实话,但它是一个很好的变通,因为角没有一个全球性的方式来做到这一点的是,除非有在1.0.3补充说,我不知道的。

You could always wrap $http in a service. Since services are only set up one time, you could just have the service factory set up the events for you. It feels a little hackish to me, honestly, but it's a good work around, since Angular doesn't have a global way to do this yet, unless something was added in 1.0.3 that I'm not aware of.

下面是它的工作一个plunker

Here's a plunker of it working

和这里的code:

app.factory('httpPreConfig', ['$http', '$rootScope', function($http, $rootScope) {
    $http.defaults.transformRequest.push(function (data) {
        $rootScope.$broadcast('httpCallStarted');
        return data;
    });
    $http.defaults.transformResponse.push(function(data){ 
        $rootScope.$broadcast('httpCallStopped');
        return data;
    })
    return $http;
}]);

app.controller('MainCtrl', function($scope, httpPreConfig) {
  $scope.status = [];

  $scope.$on('httpCallStarted', function(e) {
    $scope.status.push('started');
  });
  $scope.$on('httpCallStopped', function(e) {
    $scope.status.push('stopped');
  });

  $scope.sendGet = function (){ 
    httpPreConfig.get('test.json');    
  };
});

这篇关于AngularJS:需要每一个Ajax调用启动时开火事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆