user3188501 user3188501 - 2 months ago 10
AngularJS Question

Cannot read property 'post' of undefined angular factory

I am stuck on one problem, i use angular and got controller for send data into my factory where i have method which have to post username, login etc to my end point where i generate JWT for further use, but somehow i get this error and dont know why it even happens.

Any idea what may cause this problem?

TypeError: Cannot read property 'post' of undefined
at Object.login (Auth.js:22)
at Scope.LoginController.$scope.signIn (LoginController.js:11)

here is my factory for post request to my end point

'use strict';
angular.module("Diplomka").factory('oauth', [function oauth($http) {
'use strict';
return {
login: function (username, password) {
var token = "";
var config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}

var data = {
username: username,
password: password,
grant_type: "password"
}

$http.post("/Token", data, config)
.then(function (response) {
token = response.access_token;
});
}
};
}]);


here is my controller

'use strict';
app.controller('LoginController', ['$scope', 'oauth', '$location', LoginController]);
function LoginController($scope, oauth, $location) {


$scope.username = "";
$scope.password = "";

$scope.signIn = function () {
oauth.login($scope.username, $scope.password);
}

};

Answer

You have your "array syntax" wrong. There is a mismatch between your service names and the variables you are passing as a parameter to your factory constructor function.

'use strict';
angular.module("Diplomka").factory('oauth', ['$rootScope', '$http', function oauth($scope, $http) { // It should be like this
    // Rest of your factory here
}]);

Also, I don't think it's a good idea to inject $rootScope to your factory using the variable name $scope. Instead I would call it also $rootScope and replace all $scope references in your factory.

'use strict';
angular.module("Diplomka").factory('oauth', ['$rootScope', '$http', function oauth($rootScope, $http) { // It should be like this
    // Rest of your factory here, replacing $scope with $rootScope
}]);
Comments