karatecode
karatecode

Reputation: 594

How to use injected dependency in a angular service?

I am creating a custom service which logs a user in to my system. In this service, I need to use core services such as $http - How do I actually depend these to be used in my service?

My current code:

.factory('loginService', ['$http', '$rootScope', function() {

        var login = function(){
            console.log($http);
        }

        return {login : login};

}])

I call the login function from a controller like so

loginService.login();

I hoped that my console will output the $http object I injected, but it's returning undefined.

How do I access this in the correct way?

Upvotes: 1

Views: 98

Answers (3)

Archis
Archis

Reputation: 21

try this:

var myapp = angular.module('mainApp', []);

myapp.controller('myController', ['$scope', 'myFactory', function($scope, myFactory) {
    myFactory.login();
}]);

myapp.factory('myFactory', ['$http', function($http) {
    var services = {};

    services.login = function() {
      console.log($http);
    }

    return services;
}]);

View:

<div ng-app='mainApp' ng-controller='myController'></div>

Upvotes: 0

Jerska
Jerska

Reputation: 12042

Services you inject need to be passed as arguments of the function:

['$http', '$rootScope', function($http, $rootScope)

By the way, you'll need to do the same where you're trying to use it:

app.controller(['loginService', function (loginService) {
  loginService.login();
});

Upvotes: 0

LionC
LionC

Reputation: 3106

You need to add the dependencies to your function arguments:

.factory('loginService', ['$http', '$rootScope', function($http, $rootScope) {
    //You can use $http and $rootScope here now
}

See the official docs for more info on Dependency Injection in angular

Upvotes: 3

Related Questions