如何进行本地存储中用户名的当前用户值的角度更新

问题描述 投票:0回答:1

how to update localstorage of a currentsUser for only username when i update username its not reflecting in localstorage,am able to see the change in component page

in console application localstorage null is stored key and value is {username:gasd} it's not joining in that json. of currentUser

如何更新仅更新用户名的当前用户的本地存储,当我更新用户名时,它不反映在本地存储中,因此能够查看控制台中组件页面中的更改,获取项目的空值,并在控制台应用程序中将本地存储空值存储为密钥并且值是{username:gasd},它未加入该json。通过使用angular6

  let item =localStorage.getItem(this.currentUser);
  console.log(item);
  let myobj = {username:changeValue};
  localStorage.setItem(item, JSON.stringify(myobj));
html css angular6 typescript2.0
1个回答
0
投票

将localStorage视为键值字典。您使用string键来获取/设置string值。 (有关MDN docs的更多信息)因此,对于对象,您可以执行例如:

let myObj = {};
my["myKey"] = "myVal"; // note that in objects, values don't need to be strings
my["myKey2"] = 2;
my["myKey3"] = {};

但是在localStorage中,两边都是字符串:

localStorage.setItem("currentUser", {username: "ganes"}); // BAD
localStorage.setItem({username: "ganes"}, "someValue"); // BAD
localStorage.getItem({username: "ganes"}) // BAD

let currentUserDataStr = localStorage.getItem("currentUser"); // GOOD
// something along these lines
let currentUserData = JSON.parse(currentUserDataStr);
// do some mutation on currentUserData
currentUserData.currentUser = "ganesNew"
let newUserDataStr = JSON.stringify(currentUserData)
localStorage.setItem("currentUser", newUserDataStr); // GOOD
© www.soinside.com 2019 - 2024. All rights reserved.