AngularJS:每次启动 ajax 调用时都需要触发事件 [英] AngularJS: need to fire event every time an ajax call is started
问题描述
每次开始 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,但这是一个很好的解决方法,因为 Angular 还没有一个全局的方法来做到这一点,除非在 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.
这是代码:
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屋!