簡體   English   中英

AngularJs / .provider /如何讓rootScope進行廣播?

[英]AngularJs/ .provider / how to get the rootScope to make a broadcast?

現在我的任務是重寫$ exceptionHandler提供程序,以便它將輸出帶消息的模態對話框並停止默認事件。

我所做的:

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

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

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

})

標准注射方法不起作用。

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

您可以注入進樣器並查找$ rootScope。

演示插件: 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);  
    }
  };
});

我這樣做的方式 - 使用裝飾器並恢復到未知錯誤的先前異常處理程序:

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

你需要注入$ rootScope:

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

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

})

這是你試過的嗎? 如果是這樣,你有錯誤信息或jsfillde / plnkr,看看它失敗的原因?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM