20

我有以下代码:

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;
});

在我尝试缩小我的 javascript 然后我得到之前,这段代码可以正常工作并且符合预期

    Error: Unknown provider: eProvider <- e

这是因为我的工厂函数中的 $http 参数已重命名为 'e' 以用于缩小目的。那么如何手动通知 appModule 注入什么名称以避免缩小破坏我的代码呢?

提前致谢。

4

3 回答 3

44

尝试

appModule.factory('sharedApplication', ['$rootScope','$http',function($rootScope, $http) {

}]);

问候

于 2012-09-27T21:56:30.590 回答
2

ng-annotate也是一个很好的库,可以自动注入所需的依赖项。你应该检查一下。

代码示例:

/* 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;
});

然后你不必写:

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;
}]);
于 2014-07-09T20:43:42.213 回答
0

更优雅、更易于阅读的方法:

appModule.factory('myFactory', myFactory);

myFactory.$inject = ['$rootScope','$http'];
function myFactory($rootScope, $http) {
    ...
}
于 2017-08-03T05:35:35.357 回答