T0plomj3r
T0plomj3r

Reputation: 695

AngularJS injection Factory into Controller strange error

I've read numerous posts on stackoverflow and non of them really helped. I have strange situation where I need to inject Factory into Controller and everything seems regular but It doesnt work.

Here is factory:

zimmerApp.factory('AuthService', [function ($http, $sanitize) {
var sanitizeCredentials = function (credentials) {
    return {
        email: $sanitize(credentials.email),
        password: $sanitize(credentials.password),
        csrf_token: credentials.csrf_token
    };
};
return {
    login: function (credentials) {
        var login = $http.post("/login", sanitizeCredentials(credentials));
        login.success(cacheSession);
        login.error(loginError);
        return login;
    }
};
}]);

and controller in which I need to use AuthService is :

zimmerApp.controller('loginCtrl', ['$scope', 'AuthService',
    function ($scope, $location, AuthService) {
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "http://" + window.location.hostname + ":8000/auth/token", false);
    xhReq.send(null);

    $scope.error = false
    $scope.credentials = {
        username: '',
        password: '',
        csrf_token: xhReq.responseText
    };

    $scope.login = function (credentials) {
        AuthService.login($scope.credentials)
            .success(function () {
                $location.path('/');
            })
            .error(function (err) {
                console.log('error')
            });
    }
}]);

The error I'm getting is

TypeError: Cannot read property 'login' of undefined

so it seems like it doesn't recognize AuthService factory for some reason.

Does anyone know what could I do to fix this, I really don't have an idea anymore.

Upvotes: 0

Views: 249

Answers (1)

Enzey
Enzey

Reputation: 5254

The params being injected does not match the params in your function.

Change:

 zimmerApp.controller('loginCtrl',
     ['$scope', 'AuthService',
      function ($scope, $location, AuthService) {

To:

zimmerApp.controller('loginCtrl',
    ['$scope', $location, 'AuthService',
    function ($scope, $location, AuthService) {

I prefer not using the inject array though:

zimmerApp.controller('loginCtrl',
    function ($scope, $location, AuthService) {

Upvotes: 2

Related Questions