javascript Angularjs 通过字符串名称将提供程序注入模块工厂函数以进行缩小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12630204/
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 inject provider into module factory function by string name for minification
提问by bitwit
I have the following code:
我有以下代码:
appModule = angular.module('appModule', []);
appModule.factory('sharedApplication', function($rootScope, $http) {
var sharedApp;
sharedApp = {};
sharedApp.currentView = "home-section";
sharedApp.pastEvents = null;
$http.get('api/highlights').success(function(response) {
return sharedApp.pastEvents = response.data;
});
return sharedApp;
});
This code works perfectly and as expected until I try to minify my javascript and then I get
这段代码按预期完美运行,直到我尝试缩小我的 javascript 然后我得到
Error: Unknown provider: eProvider <- e
This is because the $http argument in my factory function has been renamed to 'e' for minification purposes. So how can I manually inform the appModule what to inject by name to avoid minification breaking my code?
这是因为出于缩小目的,我的工厂函数中的 $http 参数已重命名为“e”。那么如何手动通知 appModule 按名称注入什么以避免缩小破坏我的代码?
Thanks in advance.
提前致谢。
回答by kfis
Try
尝试
appModule.factory('sharedApplication', ['$rootScope','$http',function($rootScope, $http) {
}]);
regards
问候
回答by user3822137
ng-annotateis also a good library so that the required dependency is injected automatically. You should check it out.
ng-annotate也是一个很好的库,可以自动注入所需的依赖项。你应该检查一下。
Code sample:
代码示例:
/* ngInject */
appModule.factory('sharedApplication', function($rootScope, $http) {
var sharedApp;
sharedApp = {};
sharedApp.currentView = "home-section";
sharedApp.pastEvents = null;
$http.get('api/highlights').success(function(response) {
return sharedApp.pastEvents = response.data;
});
return sharedApp;
});
Then you don't have to write:
那么你不必写:
appModule.factory('sharedApplication', ['$rootScope','$http',
function($rootScope, $http) {
var sharedApp;
sharedApp = {};
sharedApp.currentView = "home-section";
sharedApp.pastEvents = null;
$http.get('api/highlights').success(function(response) {
return sharedApp.pastEvents = response.data;
});
return sharedApp;
}]);
回答by valmarv
The more elegant and easier to read approach:
更优雅、更易于阅读的方法:
appModule.factory('myFactory', myFactory);
myFactory.$inject = ['$rootScope','$http'];
function myFactory($rootScope, $http) {
...
}