1

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?

1
  • to me it looks like you want to do write a service instead of a factory. Commented Jul 7, 2015 at 11:03

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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();
});

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.