AngularJS错误:未知提供者:aProvider< - a

时间:2014-04-17 10:20:46

标签: javascript angularjs coffeescript gruntjs

好吧我现在已经正式秃顶了,因为这个臭名昭着的问题让我的头发脱了出来:迷你的AngularJS应用程序只是不起作用,这个错误被淘汰了:

  

错误:[$ injector:unpr]未知提供者:aProvider< - a   http://errors.angularjs.org/1.2.6/ $注射器/ unpr?P0 = aProvider%20%3 C-%20A       在http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:11492       在http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26946       at Object.c [as get](http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26250)       在http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:27041       在c(http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26250)       at Object.d [as invoke](http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:26496)       在http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:9:910       at Object.f [as forEach](http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:4:11927)       在http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:9:856       在j(http://localhost/my-app/dist/scripts/1bde0e2e.vendor.js:5:27235

很多其他人也有这个问题,但看起来可以通过将依赖关系声明为数组而不是裸函数参数来修复它,如下所示:

angular.module('my-app').controller('LoginCtrl', [ '$scope', 'HttpService', function($scope, HttpService) { ... }]);

而不是:

angular.module('my-app').controller('LoginCtrl', function($scope, HttpService) { ... });

但它在我的案例中并不起作用。我检查了所有的脚本(咖啡和生成的javascripts),它们都使用了正确的数组样式声明。

问题并非明显来自额外的包裹。我尝试将所有额外的包引用移出<!-- bower:js -->块(这样它们不会被grunt缩小),但问题仍然存在。这意味着,我的代码应该归咎于......但话又说回来,我已经尝试了(似乎只有)修复程序,但无济于事。

任何提示,即使是如何正确调试这个?

提前致谢!

3 个答案:

答案 0 :(得分:27)

最后我发现了这个问题。是的,它是我错过的DI错误。

对于可能遭受同样头痛的所有人:阵列格式声明也必须在$routeProvider的{​​{1}}选项中完成。就我而言(CoffeeScript未来):

resolve

希望这有帮助!

答案 1 :(得分:3)

如果您使用隐式注入,而不是显式声明您的依赖项,则可能会出现此行为。根据我的经验,我遇到了特殊类型的Angular.js服务的问题,这些服务返回可实例化的类(例如创建抽象控制器类或其他一些特定情况)。

例如:AbstractBaseControllerClass

在缩小期间我遇到了同样的问题。我解决了使用依赖注入的内部声明。 希望这有帮助

答案 2 :(得分:0)

对于那些不喜欢CoffeeScript的人。

我刚拿了一些代码然后把它放进去。

 $stateProvider

    .state('screen', {
        url: '/user/',
        templateUrl: 'user.html',
        controller: 'UserController',
        controllerAs: 'user',
        location: "User",
        resolve: ['$q', 'UserService', '$state', '$timeout', authenticateUser
        ]
    })

function authenticateUser($q, UserService, $state, $timeout) {

    UserService.getLoginStatus().then(function () {
        if (UserService.user) {
            console.log("is user");
            return $q.when();
        } else {
            console.log("not user");

            $timeout(function () {
                // This code runs after the authentication promise has been rejected.
                // Go to the log-in page
                $state.go('login')
            });
            return $q.reject()

        }
    });

}