javascript AngularJs/ .provider / 如何获取 rootScope 进行广播?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14954811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJs/ .provider / how to get the rootScope to make a broadcast?
提问by Stepan Suvorov
Now my task is to rewrite $exceptionHandler provider so that it will output modal dialog with message and stop default event.
现在我的任务是重写 $exceptionHandler 提供程序,以便它输出带有消息的模式对话框并停止默认事件。
What I do:
我所做的:
in project init I use method .provider:
在项目初始化中,我使用方法 .provider:
.provider('$exceptionHandler', function(){
//and here I would like to have rootScope to make event broadcast
})
standart inject method does not work.
标准注入方法不起作用。
UPD: sandbox - http://jsfiddle.net/STEVER/PYpdM/
UPD:沙箱-http: //jsfiddle.net/STEVER/PYpdM/
回答by checketts
You can inject the injector and lookup the $rootScope.
您可以注入注入器并查找 $rootScope。
Demo plunkr: http://plnkr.co/edit/0hpTkXx5WkvKN3Wn5EmY?p=preview
演示 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);
}
};
})
Update:add .provider technique too:
更新:也添加 .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);
}
};
});
回答by Amit Portnoy
My way of doing this - using a decorator and reverting to the previous exception handler on unknown errors:
我这样做的方式 - 使用装饰器并在出现未知错误时恢复到以前的异常处理程序:
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);
};
});
});
回答by martijnve
You need to inject the $rootScope:
您需要注入 $rootScope:
.provider('$exceptionHandler', '$rootScope', function(){
//and here I would like to have rootScope to make event broadcast
})
Is this what you tried? And if so do you have an error message or a jsfillde/plnkr to see why it failed?
这是你试过的吗?如果是这样,您是否有错误消息或 jsfillde/plnkr 来查看失败的原因?