2015-08-03 48 views
7

這是我的代碼。如何清除離子中的localstorage數據?

$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); 

但它不工作我的應用程序。

,這裏是我的localStorage廠

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

'access-tokan'是一個錯字,或者你在代碼中有這樣的錯誤嗎?你嘗試過使用'localstorage.clear()'(刪除'$ window')嗎? – JcDenton86

+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); 

因爲你清除它們。

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(); 
};