加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS:每次启动ajax时都需要触发事件

发布时间:2020-12-17 07:49:58 所属栏目:安全 来源:网络整理
导读:每次启动ajax调用时,我都试图在$rootScope上启动一个事件. var App = angular.module('MyApp');App.config(function ($httpProvider) { //add a transformRequest to preprocess request $httpProvider.defaults.transformRequest.push(function () { //reso
每次启动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');    
  };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读