AngularJS中是否可以使用自动依赖项注入? [英] Is automatic dependency injection available in AngularJS?
问题描述
我想自动将Angular内置服务注入Angular模块/应用程序内的所有服务中.
I want to automatically dependency inject an Angular built-in service into all services within an Angular module / app.
我要注入的服务是... $ exceptionHandler
The service I want to inject is ... $exceptionHandler
我不希望 $ exceptionHandler是全局的...例如我不想去做...
I do not want $exceptionHandler to be global ... e.g. I do not want to do ...
window.$exceptionHandler = $exceptionHandler
但是我也不想使用...手动将$ exceptionHandler注入到每个服务中.
But I also do not want to dependency inject $exceptionHandler into every service manually using ...
angular.module('myApp').factory('myService', ['$exceptionHandler', function ($exceptionHandler) {
是否可以将Angular内置服务自动注入Angular模块/应用程序内的所有服务中?
Is it possible to automatically inject an Angular built-in service into all services within an Angular module / app ?
非常感谢
推荐答案
通过嵌套模块可以使它更加方便.在根(或全局)模块中,注入$ exceptionHandler和您创建或要使用的所有其他模块.根模块的所有子模块都将注入$ exceptionHandler,而无需花费更多精力.但是,您仍然必须在控制器和工厂函数定义中命名$ exceptionHandler,因此不可能完全摆脱注入伪像.
It can be made more convenient through nested modules. In the root (or global) module inject $exceptionHandler and all the other modules you create or want to use. All sub modules of the root module will have $exceptionHandler injected without further ado. You still have to name the $exceptionHandler in your controller and factory function definitions, though, so it is not possible to completely get rid of injection artefacts.
示例:
app.js
angular.module('app', ['ionic', '$exceptionHandler', 'ngCordova','app.home',
'app.impressum'])
.run(function ($ionicPlatform, $state) {
..
})
.config(function ($stateProvider, $urlRouterProvider, $provide, $exceptionHandler, $ionicConfigProvider, $compileProvider) {
$stateProvider
.state('app', {
...
})
}
);
现在是app.home-Module:
Now the app.home-Module:
home.js
angular.module('app.home', ['app.home.controller', 'app.home.factory']);
home/controller.js
angular.module('app.home.controller', [])
.controller('homeController', function ($scope, $exceptionHandler) {
...
});
app.home.factory 和 app.impressum 的三个模块非常相似,因此我将其留给您.
app.home.factory and the three modules for app.impressum are quite similar, so I leave that to you.
如您所见,您仍然必须将$ exceptionHandler放入控制器的函数参数中,但是模块本身不需要注入,因为它继承了其父模块 app.home 和 app .
As you can see you still have to put $exceptionHandler into the function parameters of your controller, but no injection is required on the module itself, because it inherits all injections from it's parent modules app.home and app.
通过在AngularJS应用程序中使用模块的层次结构,可以在适当的时候进行注入...对于整个应用程序,模块组或仅在单个模块上,更具全局性.此外,我们的应用程序部分结构非常简洁.
By using a hierarchy of modules in an AngularJS app injections can be made where due... more globally for the whole app, for module groups or only on single modules. Plus we get a very clean structure for the App's sections.
这篇关于AngularJS中是否可以使用自动依赖项注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!