我有一个角度$resource
用于登录并获取用户的信息。登录名将用户名和密码发送给服务器并获取Bearer令牌。在success
User.login
函数中,令牌存储在localStorage
中。在getEmail
中,我将标记包含在用户电子邮件地址的标题中。
问题是,第一次在控制器中调用getEmail
,$window.localStorage.getItem('TK')
评估为null
,但如果我刷新页面,那么它可以正常工作。包含令牌的服务器的所有后续请求都按预期工作。什么可能导致这种情况?
更不用说,getEmail
在登录后被称为方式,我确认在调用localStorage
之前getEmail
中存在该令牌。
angular.module('authentication')
.factory('User', function ($resource, $window) {
return $resource('/login', {}, {
login: {
method: 'POST'
},
getEmail: {
url: '/user',
method: 'GET',
headers: {
'Authorization': "Bearer " + $window.localStorage.getItem('TK')
}
}
});
})
回应@评论: 我的控制器看起来像这样:
angular
.module('app.mymodule', ['ngReource', 'authentication')
.controller('myCtrl', mymodule);
mymodule.$inject = ['User', '$window'];
function mymodule(User, $window) {
// THIS PRINTS THE TK IN CONSOLE CORRECTLY
console.log($window.localStorage.getItem("CHTOKEN"));
// THIS IS UNAUTHORIZED CUZ TK IS NULL
User.getEmail({}, function(data){
console.log('set the email');
});
}
答案 0 :(得分:4)
您的问题是资源定义是在创建时(保存令牌之前)提供的。
您可以向$httpProvider
添加常规request interceptor,以便涵盖所有请求或更改getEmail
操作header
以使用某个功能,以便在运行时对其进行评估时间,例如
headers: {
'Authorization': function() {
var token = $window.localStorage.getItem('TK');
return token ? 'Bearer ' + token : null;
}
}