AngularJS - 缩小错误

时间:2014-09-24 19:23:44

标签: javascript angularjs minify

我正试图在我的角应用程序中缩小我的js文件。我知道在依赖注入和缩小时有一些pbs,但我觉得我遵循了我在互联网上找到的最佳实践。

这是我的代码的结构:

我的提供者:

function myPvdr() {
  this.getUrl = function() {
    return 'http://some/api/call';
  };
  this.$get = function($q, $http) {
    var self = this;
    return {
      getData: function(points) {
        var d = $q.defer();
        $http({
          method: 'GET',
          url: self.getUrl(),
          cache: true
        }).success(function(data) {
          d.resolve(data);
        }).error(function(err) {
          d.reject(err);
        });
        return d.promise;
      }
    }
  }
}

我的控制器:

function myCtrl($scope, MyProvider, localStorageService) {
     // some code
}

我的模块:

angular.module('myApp', ['LocalStorageModule', 'ngAnimate'])
  .provider('MyProvider', myPvdr)

  // Loading controllers into the module
  .controller('myCtrl', ['$scope', 'MyProvider', 'localStorageService', myCtrl])

在未经宣传时它可以正常工作。但是在使用grunt中的uglify任务后,我将以下错误打印到控制台:

Error: [$injector:unpr] http://errors.angularjs.org/1.3.0-rc.2/$injector/unpr?p0=aProvider%20%3C-%20a%20%3C-%20MyProvider

我做错了什么?

2 个答案:

答案 0 :(得分:3)

您没有安全地使用代码:

有两个选项,当你声明函数并使用带引号的数组的引号时,$ inject或添加内联(引号中的东西不会缩小)

https://docs.angularjs.org/tutorial/step_05

在控制器函数上创建一个$ inject属性,该函数包含一个字符串数组。数组中的每个字符串都是要为相应参数注入的服务的名称。在我们的例子中,我们会写:

function PhoneListCtrl($scope, $http) {...}
PhoneListCtrl.$inject = ['$scope', '$http'];
phonecatApp.controller('PhoneListCtrl', PhoneListCtrl);

使用内联注释,而不是仅提供函数,而是提供数组。该数组包含服务名称列表,后跟函数本身。

function PhoneListCtrl($scope, $http) {...}
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', PhoneListCtrl]);

答案 1 :(得分:1)

如果您已经在使用grunt,请考虑使用grunt-ng-annotate task。 ng-annotate是一种工具,可以在需要的地方自动插入适当的缩小准备语法。