StepUp StepUp - 2 months ago 58
Javascript Question

How to properly inject a dependency in Angular module in Web API?

I have a objectFactory.js file:

(function () {
var objectiveFactory = function ($http, $ngAnimate) {
debugger;
return {
getObjectives: function () {
return $http.get('/api/Objective/');
}
};

};
debugger;
try {
//objectiveFactory.$inject = ['$http', '$ngAnimate'];// not working
objectiveFactory.$inject = ['$http'];// perfectly works!
angular.module('app', []).factory('objectiveFactory', objectiveFactory);
}
catch (e)
{
var e1 = e;
}

}());


It is really weird, however if I add new dependency
ngAnimate
:

objectiveFactory.$inject = ['$http', '$ngAnimate'];// not working


Then I've got an error:


angular.js:13920 Error: [$injector:unpr] Unknown provider:
ngAnimateProvider <- ngAnimate <- objectiveFactory
http://errors.angularjs.org/1.5.8/$injector/unpr?p0=ngAnimateProvider%20%3C-%20ngAnimate%20%3C-%20objectiveFactory
at angular.js:68
at angular.js:4511
at Object.getService [as get] (angular.js:4664)
at angular.js:4516
at getService (angular.js:4664)
at injectionArgs (angular.js:4688)
at Object.invoke (angular.js:4710)
at Object.enforcedReturnValue [as $get] (angular.js:4557)
at Object.invoke (angular.js:4718)
at angular.js:4517


But
'$http'
injecion perfectly works.


I've explored a lot of info and double checked the following advices in my Web API application:


  1. I've checked versions
    angular'js
    file and
    angular-animate.js
    and they are the same 1.5.8.

  2. I've excluded minification and bundling, so files are loaded like the following code snippet:

    <script src="@Url.Content("~/Scripts/jquery-1.10.2.js")"></script>
    <script src="@Url.Content("~/Scripts/bootstrap.js")"></script>
    <script src="@Url.Content("~/Scripts/angular.js")"></script>
    <script src="@Url.Content("~/Scripts/angular-route.js")"></script>
    <script src="@Url.Content("~/Scripts/angular-animate.js")"></script>
    <script src="@Url.Content("~/Scripts/objectiveFactory.js")"></script>
    <script src="@Url.Content("~/Scripts/objective.js")"></script>



However, the error is the same:


angular.js:13920 Error: [$injector:unpr] Unknown provider:


Does anybody know what I've done wrong? (
'$http'
injecion perfectly works)

Answer

ngAnimate is the module name not the service you are trying to inject. If you want to use animate service you should inject $animate instead of ngAnimate.

objectiveFactory.$inject = ['$http', '$animate'];
Comments