[英]AngularJS “localStorage.getItem” is null in $resource
我有一個角度$resource
用於登錄和獲取用戶的信息。 登錄名將用戶名和密碼發送給服務器並獲取Bearer令牌。 在User.login
的success
函數中,令牌存儲在localStorage
。 在getEmail
,我將標頭中的令牌包含在用戶的電子郵件地址中。
問題是,第一次在控制器中調用getEmail
, $window.localStorage.getItem('TK')
計算結果為null
但是如果我刷新頁面則它可以正常工作。 包含令牌的服務器的所有后續請求都按預期工作。 什么可能導致這個?
更不用說, getEmail
在登錄getEmail
稱為方式,我已經確認在調用getEmail
之前令牌存在於localStorage
。
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')
}
}
});
})
回應@ comment:我的控制器看起來像這樣:
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');
});
}
您的問題是在創建時(保存令牌之前)提供了資源定義。
您可以向$httpProvider
添加一般請求攔截器 ,以便覆蓋所有請求或更改您的getEmail
操作的header
以使用函數,以便在運行時對其進行評估,例如
headers: {
'Authorization': function() {
var token = $window.localStorage.getItem('TK');
return token ? 'Bearer ' + token : null;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.