I am trying to implement login module to AngularJS app. I try to call UserService from (this) authenticationService but UserService is undefined. What am I doing wrong now, why UserService is undefined?
var authenticationService = angular.module('authenticationService', []);
authenticationService.factory('authenticationSvc', ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService',
function AuthenticationService($scope, $http, $cookieStore, $rootScope, $timeout, UserService) {
var service = {};
service.Login = Login;
service.SetCredentials = SetCredentials;
service.ClearCredentials = ClearCredentials;
return service;
function Login(username, password, callback) {
var response;
UserService.GetByUsername(username) //UserService is unidefined!!!
.then(function (user) {
if (user !== null && user.password === password) {
response = { success: true };
} else {
response = { success: false, message: 'Username or password is incorrect' };
}
callback(response);
});
}
EDIT : Take a look at your dependency injection: you should have the same number of elements in the dependency array as the number of arguments in your function. You inject $scope
in the array, and not in the arguments. You should always inject every dependency in both, and in the right order: here, Angular thinks $scope
corresponds to your $http
argument, the $http
service corresponds to your $cookieStore
argument, and so on, until UserService
that refers to the 6th element of the dependency array which is... undefined.
Try
authenticationService.factory('authenticationSvc', ['$scope','$http', '$cookieStore', '$rootScope', '$timeout', 'UserService',
function AuthenticationService($scope, $http, $cookieStore, $rootScope, $timeout, UserService) {
...
}
]);
Instead.
Also, with this line
var authenticationService = angular.module('authenticationService', []);
You create a new module that has no dependencies ( []
) my guess is that UserService
is defined in another module, that is not injected in the present service module nor in the app's main module, thus unavailable.
For the record : angular.module(name,array)
creates a new module, which depends on the modules passed in the array. angular.module(name)
retreives a previously created module.
I don't think you need a new module for a single service though. If you define your Authentication service in the same module as your UserService
, it will be available by default.
EDIT : Plus, be careful with your naming pattern : for instance, given your code, if I wanted to include the authentication service as a service dependency, I would have to include authenticationSvc
and not authenticationService
...
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.