我正在尝试从 $resource 创建服务,因为请求需要身份验证,所以我发送了一个 Authorization header 。
所以我有 2 项服务:
- authService
- 用户信息服务
授权服务:
var ouveerApiServices = angular.module('ouveerServices.api', []);
ouveerApiServices.factory('authService', ['$http', '$rootScope', 'localStorageService', 'apiService',
function($http, $rootScope, localStorageService, apiService){
return {
isLogged : function(){
return (localStorageService.get('accessToken')) ? true : false;
},
logIn : function(email, password){
var dataQuery = $.param({
grant_type: "password",
username : email,
password : password
});
return $http({
url: $rootScope.apiURL + 'Auth',
method: 'POST',
data : dataQuery,
withcredentials : true,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
}
});
},
logOut : function(){
return apiService.post({ url: 'api/Account/Logout' });
},
getAccessToken : function(){
return localStorageService.get('accessToken');
}
} //return
} //function
]);
还有 userInfoService:
var ouveerUserServices = angular.module('ouveerServices.user', []);
//user related queries
ouveerApiServices.factory('userInfoService', ['$resource', '$rootScope', 'localStorageService', 'authService',
function($resource, $rootScope, localStorageService, authService){
return $resource($rootScope.apiURL + 'api/users/:userId', { userId : '@id' }, {
update : {
method: 'PUT',
isArray : false
},
account : {
method : 'GET',
isArray : false,
url: $rootScope.apiURL + 'api/Account/UserInfo',
headers : {
'Authorization' : 'Bearer ' + authService.getAccessToken()
}
}
});
}
]);
问题出现在我调用时(在 Controller 中):
$scope.signIn = function(){
$scope.messages = [];
console.log($scope.user.semail);
if($scope.user.semail && $scope.user.spassword){
authService.logIn($scope.user.semail, $scope.user.spassword).success(function(data){
localStorageService.add('accessToken', data.access_token);
console.log(authService.getAccessToken());
//setting userID in localstorage
userInfoService.account(function(){
localStorageService.add('userId', userData.userId);
$location.path('/library');
});
}).error(function(){
$scope.status = 'error';
$scope.messages[0] = ['Review the fields please, something is wrong...'];
});
} else {
$scope.status = 'error';
$scope.messages[0] = ['Type your email and password.'];
}
}
它返回 null,但正如您所注意到的,我在调用 userInfoService 之前转储了 var,并且它响应了身份验证代码,我做错了什么吗?
最佳答案
请注意,您可以通过以下方式初始化帐户属性:
account : {
method : 'GET',
isArray : false,
url: $rootScope.apiURL + 'api/Account/UserInfo',
headers : {
'Authorization' : 'Bearer ' + authService.getAccessToken()
}
}
此代码(包括 authService.getAccessToken()
)在服务创建时运行,即早于 Controller 中的代码运行。因此,authService.getAccessToken()
已解析,并且在该时间点它为 null。
换句话说,当您尝试实际使用帐户资源中的 header 时,它只是一个很久以前创建的字符串。
关于javascript - Angujar JS 中一个服务的响应在另一个服务中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797021/