每次启动ajax调用时,我都试图在$rootScope上启动一个事件.
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呼叫开始时,如何获取事件,而不用在每次打电话时传递配置对象?
提前致谢
您可以随时在服务中包装$http.由于服务只设置一次,您可以让服务工厂为您设置事件.对我来说,诚实地感觉到一点点黑客,但这是一个很好的工作,因为Angular并没有一个全球性的方法去做,除非在1.0.3中添加了我不知道的内容.
Here’s a plunker of it working
这里是代码:
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'); }; });