AngularJs / .provider /如何让rootScope使广播?(AngularJs/

2019-08-17 01:13发布

现在我的任务是重写$ exceptionHandler的供应商,使其与消息输出模式对话框,停止违约事件。

我所做的:

项目初始化我用的方法.provider:

.provider('$exceptionHandler', function(){

//and here I would like to have rootScope to make event broadcast

})

非标准注入方法不起作用。

UPD:沙盒- http://jsfiddle.net/STEVER/PYpdM/

Answer 1:

你可以注入进样器和查找的$ rootScope。

演示plunkr: http://plnkr.co/edit/0hpTkXx5WkvKN3Wn5EmY?p=preview

myApp.factory('$exceptionHandler',function($injector){
    return function(exception, cause){
        var rScope = $injector.get('$rootScope');
        if(rScope){
            rScope.$broadcast('exception',exception, cause);
        }
    };
})

更新:新增.provider技术太:

app.provider('$exceptionHandler', function() {
  // In the provider function, you cannot inject any
  // service or factory. This can only be done at the
  // "$get" method.

  this.$get = function($injector) {
    return function(exception,cause){
      var rScope = $injector.get('$rootScope');
      rScope.$broadcast('exception',exception, cause);  
    }
  };
});


Answer 2:

我这样做的方式 - 使用装饰和恢复对未知错误的上述异常处理程序:

app.config(function ($provide) {
  $provide.decorator('$exceptionHandler', function($delegate, $injector) {
    return function (exception, cause) {
      if (ICanHandleThisError) {
        var rootScope= $injector.get('$rootScope');
        // do something (can use rootScope)
      } else
       $delegate(exception, cause);
    };
  });
});


Answer 3:

您需要注入$ rootScope:

.provider('$exceptionHandler', '$rootScope', function(){

//and here I would like to have rootScope to make event broadcast

})

这是你尝试过什么? 如果是的话,你有一个错误信息或jsfillde / plnkr明白为什么会失败?



文章来源: AngularJs/ .provider / how to get the rootScope to make a broadcast?