我想實現登錄模塊到AngularJS應用程序。我嘗試從(this)authenticationService調用UserService,但UserService未定義。我現在做錯了什麼,爲什麼UserService是未定義的?在AngularJS中注入服務到另一個服務
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);
});
}
所以當我調用工廠並嘗試向UserService添加依賴關係時,這還不夠? – Sami
如果他們在同一個模塊中就足夠了。但他們不是。相反,您必須將模塊作爲模塊依賴項注入,然後將服務本身作爲服務依賴項。 – Tiesselune
@Sami Tiesselune是正確的,通過建議的設計,你應該保持在同一模塊中的所有服務 –