【问题标题】:AngularJs/ .provider / how to get the rootScope to make a broadcast?AngularJs/.provider/如何获取rootScope进行广播?
【发布时间】:2013-02-03 23:25:44
【问题描述】:

现在我的任务是重写 $exceptionHandler 提供程序,以便它输出带有消息的模式对话框并停止默认事件。

我做什么:

在项目初始化中我使用方法 .provider:

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

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

})

标准注入方法不起作用。

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

【问题讨论】:

    标签: javascript angularjs broadcast provider


    【解决方案1】:

    您可以注入注入器并查找 $rootScope。

    Demo 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);  
        }
      };
    });
    

    【讨论】:

    【解决方案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);
        };
      });
    });
    

    【讨论】:

      【解决方案3】:

      你需要注入 $rootScope:

      .provider('$exceptionHandler', '$rootScope', function(){
      
      //and here I would like to have rootScope to make event broadcast
      
      })
      

      这是你尝试的吗?如果是这样,您是否有错误消息或 jsfillde/plnkr 来查看失败的原因?

      【讨论】:

      • 是的,但如果它不起作用,您要么使用错误,导致它没有可见的效果,要么应该产生错误。如果您制作 jsfiddle,我们会更容易为您提供帮助。
      • 致那些一直反对我的人:我要求的信息是在我要求之后才添加的。然后 OP 指责我要求提供他已经添加的信息。
      猜你喜欢
      • 2013-09-22
      • 2016-01-27
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      相关资源
      最近更新 更多