I've created a service that needs to listen for $route
events. I'm setting listeners with $rootScope.$on()
. My service looks like this:
我创建了一个需要侦听$route事件的服务。我用$rootScope设置监听器,$on()。我的服务是这样的:
application.factory('myListener', ['$rootScope', function ($rootScope) {
$rootScope.$on('$routeChangeStart', myListener.onChangeStart);
return {
onChangeStart: function() {
// Do something.
}
};
}]);
It works OK, but I have to inject instance of this service at least once somewhere in my application in order for listener to attach itself.
它可以正常工作,但是我必须在应用程序中至少有一次注入这个服务的实例,以便侦听器附加自己。
Is there a way to force-create the instance without injecting it somewhere?
有没有一种方法可以强制创建实例而不将其注入到某个地方?
Maybe you could recommend a better way to structure this service?
也许你可以推荐一种更好的方式来构建这个服务?
Thank you.
谢谢你!
2 个解决方案
#1
1
If you don't need the service, but rather some code that runs when the application starts, then you should put it into a run block:
如果您不需要该服务,而是需要一些应用程序启动时运行的代码,那么您应该将其放入运行块中:
application.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeStart', function() {
// Do something.
});
}]);
#2
2
angular.injector().get('myListener');
should give you the instance of the service.
angular.injector(). get(“myListener”);应该给您服务的实例。
#1
1
If you don't need the service, but rather some code that runs when the application starts, then you should put it into a run block:
如果您不需要该服务,而是需要一些应用程序启动时运行的代码,那么您应该将其放入运行块中:
application.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeStart', function() {
// Do something.
});
}]);
#2
2
angular.injector().get('myListener');
should give you the instance of the service.
angular.injector(). get(“myListener”);应该给您服务的实例。