从本地存储中获取对象 Angular 8

Get object from Local Storage Angular 8

我有一个正在存储一些数据的本地存储。我正在尝试使用 localStorage.getItem('id'); 获取组件中的数据,但它未定义。问题是,localStorage 以一种奇怪的格式存储 id。它存储为 abcabcabc.id 现在在 localStorage 中有多个这样的参数,并且对于每个登录用户,字符串 abcabcabc 都会更改。我怎样才能仍然获得 id 值。我可以比较字符串或其他东西来获取值吗?就像如果它包含字符串 .id 只读取那个值?如果是,您能否解释一下如何实现?

本地存储:

abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg

localStorage 将数据设置为键值对的映射,因此:

var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string 
localStorage.setItem('id', JSON.stringify(id));

现在您可以通过以下方式获取数据:

var getTheId = localStorage.getItem('id');
//you can use JSON.parse() if you need to print it
console.log('getTheId: ', JSON.parse(getTheId));

这是您通常的做法,但由于我不知道您是如何设置数据的,因此您可以通过以下方式获取数据:

var x = localStorage.getItem(id);//normally getting your id
//parse it
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//this is to only get the abcabacabc
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);

由于您不知道存储在 localStorage 中的确切密钥,因此请获取所有这些密钥,然后对其进行迭代。接下来,匹配您知道的部分密钥,即 id,如下图所示:

// fetch all key-value pairs from local storage
const localStorageKeys = { ...localStorage };

// iterate over them
for (const index in localStorageKeys) {

  // see if key contains id
  if (index.includes('id')) {

    // fetch value for corresponding key 
    console.log(localStorageKeys[index]);

  }
}