Javascript 提供程序中的$rootScope
我无法在提供程序中访问$rootScope。我查看了许多其他模块的实现。这与我实现的方式相同。 怎么了? 它尝试将urload作为一个单独的函数(类似于其他getValue函数),但它不起作用 错误为$emit未定义Javascript 提供程序中的$rootScope,javascript,angularjs,dependency-injection,Javascript,Angularjs,Dependency Injection,我无法在提供程序中访问$rootScope。我查看了许多其他模块的实现。这与我实现的方式相同。 怎么了? 它尝试将urload作为一个单独的函数(类似于其他getValue函数),但它不起作用 错误为$emit未定义 define(['angularAMD'], function () { var contextServiceModule = angular.module('contextService', []); var contextService =
define(['angularAMD'], function () {
var contextServiceModule = angular.module('contextService', []);
var contextService = function () {
var context = {};
this.$get = ['$rootScope', function ($rootScope) {
console.log($rootScope);
return function (){
return {
init: init,
getValue: getValue,
setValue: setValue,
urlLoad: function () {
$rootScope.$emit('onInit', {});/// error here
}
};
};
}];
this.init = function () {
return context;
};
this.getValue = function (key) {
var value = context[key] ? context[key] : null;
return value;
};
this.setValue = function (key, value) {
context[key] = value;
};
}
contextServiceModule.provider('contextService', contextService);
});
角度提供程序在配置阶段创建,$rootScope在应用程序运行阶段才可用。这里有一些关于它的资料和一个类似的问题:
无法将$rootScope注入提供程序$get函数,因为该函数尚不可用。但是,您可以在调用函数时手动注入它
this.$get = ['$injector', function ($injector) {
return function (){
return {
init: init,
getValue: getValue,
setValue: setValue,
urlLoad: function () {
var $rootScope = $injector.get('$rootScope');
console.log($rootScope);
$rootScope.$emit('onInit', {});/// error here
}
};
};
}];
这就是为什么我得到$rootScope来广播消息,从
React.js
到Angular
。
如果您的ng视图
不在主体中,请使用您的视图
function $broadcast(event, args]) {
angular.element('body').injector().invoke([
'$rootScope',
'$timeout',
($rootScope, $timeout) =>
{
args.unshift(event);
$timeout(() => {
$rootScope.$broadcast.apply($rootScope, args);
});
}
]);
}
从这里得到:
!!重要提示:缩小后,以下解决方案不起作用。为此,您需要进行依赖项注入,但在配置阶段无法调用$get
app.provider('someHandler', function() {
this.$get = function ($rootScope) {
function doBroadcast(words) {
$rootScope.$broadcast(words);
}
return {
shout: function (words) {
doBroadcast(words);
}
}
}
});
如果需要在配置阶段使用,可以执行以下操作
app.config(['someHandlerProvider', function(someHandlerProvider) {
someHandlerProvider.$get().shout('listen up');
}
在跑步过程中您只需执行someHandler.shout('listen up')