Finding the cause of “Unknown provider” errors

后端 未结 4 707
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 20:57

I\'m getting the following error:

Error: [$injector:unpr] Unknown provider: nProvider <- n

I know this is being caused by the minifi

4条回答
  •  囚心锁ツ
    2021-01-30 21:43

    Angular's injector has 3 ways to resolve dependencies for you:

    1. Inferring dependencies from function argument names. This is most used in all angular's examples, e.g.

    app.controller('MyController', function($scope, MyService) { ... });
    

    In this case injector casts function as string, parses argument names and looks for services/factories/anything-else matching that name.

    2. Inline annotations. You might also encounter this syntax:

    app.controller('MyController', ['$scope', 'MyService', function($scope, MyService) { ... }]);
    

    In this case you make it much easier for the injector, since you explicitly state names of dependencies you require. The names are enclosed in quotes and js minifiers do not modify strings in code.

    3. Inline annotations as property. If you define your controllers as functions, you might set annotations in special property $inject:

    function MyController($scope, MyService) {...}
    MyController.$inject = ['$scope', 'MyService'];
    

    In this case we also explicitly state dependencies.

    My guess is you're using the solution no. 1. Once minifier changes names of your implicitly defined dependencies, injector no longer knows, what are your function's dependencies. To overcome this you should use 2nd or 3rd way of annotating dependencies.

提交回复
热议问题