[英]Injecting service to another service in AngularJS
我正在尝试将登录模块实现为AngularJS应用。 我尝试从(this)authenticationService调用UserService,但未定义UserService。 我现在在做什么错,为什么未定义UserService?
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);
});
}
编辑:看看您的依赖项注入:您应该在依赖项数组中的元素数与函数中参数的数量相同。 您在数组中而不是在参数中注入$scope
。 您应该始终以正确的顺序同时注入每个依赖项:在这里,Angular认为$scope
对应于$http
参数, $http
服务对应于$cookieStore
参数,依此类推,直到UserService
指向第6个未定义的依赖项数组的元素。
尝试
authenticationService.factory('authenticationSvc', ['$scope','$http', '$cookieStore', '$rootScope', '$timeout', 'UserService',
function AuthenticationService($scope, $http, $cookieStore, $rootScope, $timeout, UserService) {
...
}
]);
代替。
另外,用这条线
var authenticationService = angular.module('authenticationService', []);
您创建了一个没有依赖项( []
)的新模块,我的猜测是UserService
是在另一个模块中定义的,该模块未注入到当前服务模块或应用程序的主模块中,因此不可用。
记录: angular.module(name,array)
创建一个新模块,该模块取决于数组中传递的模块。 angular.module(name)
检索以前创建的模块。
我认为您不需要为单个服务使用新模块。 如果您在与UserService
相同的模块中定义身份验证服务,则默认情况下它将可用。
编辑:另外,请注意您的命名模式:例如,给定您的代码,如果我想将身份验证服务作为服务依赖项包含在内,则必须包含authenticationSvc
而不是authenticationService
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.