How to clear localstorage data in ionic?

arun kamboj picture arun kamboj · Aug 3, 2015 · Viewed 35.2k times · Source

Here is my code.

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

I want to delete the access-token variable from my localStorage, It working fine for browser when i use

 $window.localStorage.clear();
 $window.localStorage.removeItem(access-token);

But its not working for my App.

here is my localstorage factory

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] || '{}');
        }
    }

}]);

Any Idea?

Answer

Hitu Bansal picture Hitu Bansal · Aug 4, 2015

I had also faced same problem mean time ago. I was using some Global variable for Local Storage. Your code seems ok. But you can optimize it better

$scope.logout = function(){
  $window.localStorage.clear();
    $ionicHistory.clearCache();
    $ionicHistory.clearHistory();
 };

You don't need to set

localstorage.set('user_id', "");
localstorage.set('access-token', "");
localstorage.set('isUserTraverseColony', 0);
localstorage.set('isStarted', 0);

because you are clearing them.