这是我的代码。
$scope.logout=function(){
localstorage.set('user_id', "");
localstorage.set('access-token', "");
localstorage.set('isUserTraverseColony', 0);
localstorage.set('isStarted', 0);
$window.localStorage.clear();
$window.localStorage.removeItem(access-token);
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
};
我想从我的localStorage中删除访问令牌变量,当我使用它时它适用于浏览器
$window.localStorage.clear();
$window.localStorage.removeItem(access-token);
但它不能用于我的应用程序。
这是我的本地存储工厂
angular.module('starter.controllers').factory('localstorage', ['$window', '$localStorage','$q', function ($window, $localStorage,$q) {
return {
set: function (key, value) {
var deferred = $q.defer();
$window.localStorage[key] = value;
deferred.resolve(1);
return deferred.promise;
},
get: function (key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
setObject: function (key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function (key) {
return JSON.parse($window.localStorage[key] || '{}');
}
}
}]);
任何想法?
答案 0 :(得分:6)
我平均也遇到过同样的问题。我正在使用一些全局变量进行本地存储。 你的代码似乎没问题。但你可以更好地优化它
$scope.logout = function(){
$window.localStorage.clear();
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
};
您不需要设置
localstorage.set('user_id', "");
localstorage.set('access-token', "");
localstorage.set('isUserTraverseColony', 0);
localstorage.set('isStarted', 0);
因为你正在清除它们。
答案 1 :(得分:4)
您可以将clear()
方法添加到自定义localstorage
服务中:
angular.module('starter.controllers').factory('localstorage', ['$window', '$localStorage','$q', function ($window, $localStorage,$q) {
return {
set: function (key, value) {
$window.localStorage.setItem(key, value);
},
get: function (key, defaultValue) {
return $window.localStorage.getItem(key) || defaultValue;
},
setObject: function (key, value) {
$window.localStorage.setItem(key, JSON.stringify(value));
},
getObject: function (key) {
return JSON.parse($window.localStorage.getItem(key) || '{}');
},
clear: function () {
$window.localStorage.clear();
}
}
}]);
注意:我更新了您的服务删除承诺,因为HTML5 localStorage is syncronous并使用标准的get和set方法
然后在你的控制器中:
$scope.logout = function(){
localstorage.clear();
$ionicHistory.clearCache();
$ionicHistory.clearHistory();
};