javascript 离子本地存储删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30315791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:02:17  来源:igfitidea点击:

Ionic local storage remove item

javascriptionic-framework

提问by Joseph Ocasio

Can someone help me to create a method to remove from ionic local storage?

有人可以帮我创建一种从离子本地存储中删除的方法吗?

So far I have tried

到目前为止我已经尝试过

    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    get: function(key) {
      return $window.localStorage[key];
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
      return JSON.parse($window.localStorage[key]);
    },
    removeItem: function(key){
      $window.localstorage.splice(key, 1);
    }

removeItem doesnt work at all. I want to remove by positions, not by key.

removeItem 根本不起作用。我想按位置删除,而不是按键删除。

回答by devqon

You are using localStorageas an array, while it isn't. It has default functions to remove an item:

您正在使用localStorage数组,而事实并非如此。它具有删除项目的默认功能:

removeItem: function(key){
    $window.localStorage.removeItem(key);
}

If you want to remove by index, you have to get the item first:

如果要按索引删除,则必须先获取项目:

removeByIndex: function (index) {
    $window.localStorage.removeItem($window.localStorage.key(index));
}

回答by Divyesh

Try the built in methods, which will help to complete the whole transaction of the removal of your key:valuefrom LocalStorage

尝试内置方法,这将有助于完成key:valueLocalStorage

https://auth0.com/docs/native-platforms/ionic#8

https://auth0.com/docs/native-platforms/ionic#8

回答by NHTorres

This would be the best way. With this factory you can create, retrieve, or delete any created key

这将是最好的方法。使用此工厂,您可以创建、检索或删除任何已创建的密钥

.factory('sessionService',['$http',function($http){
  return {
     set:function(key,value){
     return localStorage.setItem(key,JSON.stringify(value));
   },
   get:function(key){
     return JSON.parse(localStorage.getItem(key));
   },
   destroy:function(key){
     return localStorage.removeItem(key);
   },
 };
}])