简体   繁体   中英

Unable to inject $http into a factory

I'm trying to inject $http into a factory but i'm getting this error:

Error: Unknown provider: $httpProvider <- $http <- utilService

Here is my factory code:

var util = angular.module('util', [])
.factory('utilService', ['$http', function($http) {             
    return {
        translate: function(objects, prop) {
            var keys = objects.map(function(o) {return o[prop];});      
            $http({method: 'POST', url: 'http://localhost:8080/rest/messages', data: keys}).
            success(function(data, status, headers, config) {
                return objects.map(function(o, rank) {return {'value': data[rank], 'object': o}});
            });
        }
    };
}]);

The code of the controller where i use the service:

var app = angular.module('recordController', ['ui.bootstrap','dialogs', 'util']);

function records($scope, $http, $rootScope, $timeout, $dialogs) {

  var utilService = angular.injector(['util']).get('utilService');

  $scope.showForm = false;
  $scope.states= [];

  $scope.toggleForm = function() {
    $scope.showForm = !$scope.showForm;

    if($scope.showForm) {
        if(!$scope.states.length) {
            $http({method: 'GET', url: 'http://localhost:8080/rest/records/state'}).
            success(function(data, status, headers, config) {
                $scope.states = utilService.translate(data, 'state');   
            });
        }
    }
  };

  ...
};

And the HTML :

    <div ng-app='recordController'>
      <div ng-controller='records' >    
        ...
      </div>
    </div>

Is something wrong with it? I have been searching for some insight in StackOverflow and Google but couldn't find any hint about what's wrong.

I haven't really tested any of this but I believe your problem can be fixed in multiple ways:

1

Use angular.module('util', ['ng']) instead of angular.module('util', []) .

2

Use app.get('utilService') instead of angular.injector(['util']).get('utilService') .

3

Get rid of var utilService = angular.injector(['util']).get('utilService'); and add utilService as the last parameter of the records function. I'm not really sure this works as I normally don't use this form of declaration.

If #3 works, use that, if not use #2. Use #1 only if you have to.

Also, you did not post the part of the code where records is used, but make sure you are using the array notation for dependencies otherwise you'll have issues when mangling the code with UglifyJS or similar too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM