存储服务存储在 localStorage 中但无法检索它

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

我有一个 Angular 服务,它成功存储键和值,但无法检索它。下面是代码:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class StorageService {
  constructor() {}

  // Store the value - (Note: This code works fine.  The key is userData and it stores an array of user credentials as value )

  async store(storageKey: string, value: any) {
    localStorage.setItem('key', storageKey);
    localStorage.setItem('value', value);
  }
  
  // Get the value - Here I provide the userData as key but I get a null value.  If put key in "key" then I get an error.  I have verified with console.log(key) that accurate key is passed to retrieve the value.

  async get(key: string) {
    const ret = localStorage.getItem(key);
    return JSON.parse(ret);
  } 
}

angular local-storage angular17
2个回答
0
投票

您在 StorageService 中遇到的问题在于您如何在 localStorage 中存储和检索值。

在 store 方法中,您使用字符串“key”和“value”作为 localStorage 中的键,而不管传递的 storageKey 和 value 是什么。这意味着您会不断覆盖本地存储中的相同密钥。

要解决此问题,您应该使用作为参数传递的 storageKey 和 value 变量,而不是固定字符串“key”和“value”。存储方法应该是这样的:

async store(storageKey: string, value: any) {
  localStorage.setItem(storageKey, JSON.stringify(value));
}

在此代码中,我们使用 storageKey 变量作为实际键来存储提供的值。此外,我们在将值存储到 localStorage 之前已将该值转换为 JSON 字符串。

另一方面,在 get 方法中,您尝试使用 key 键检索值。这是不正确的;您应该使用提供的密钥作为关键参数。 get 方法应该是这样的:

async get(key: string) {
  const ret = localStorage.getItem(key);
  return ret ? JSON.parse(ret) : null;
}

现在,当您调用 store 并输入代码时,请确保传递正确的键来存储和检索值。例如:

// Store a value
storageService.store('userData', yourData);

// Retrieve a value
const userData = storageService.get('userData');

0
投票

请在一次调用中使用

set
localStorage
方法,将键和值一起调用,您需要
JSON.stringify
值才能正确存储它!

那么在获取值的时候,我们就可以正确获取值,并且很容易解析!

我不确定为什么我们需要异步等待,因为所有 localStorage 调用都是同步的。我们也可以删除它们!

服务

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class StorageService {
  constructor() {}

  // Store the value - (Note: This code works fine.  The key is userData and it stores an array of user credentials as value )

  store(storageKey: string, value: any) {
    console.log(storageKey, value);
    localStorage.setItem(storageKey, JSON.stringify(value));
  }

  // Get the value - Here I provide the userData as key but I get a null value.  If put key in "key" then I get an error.  I have verified with console.log(key) that accurate key is passed to retrieve the value.

  get(key: string) {
    console.log(key);
    const ret = localStorage.getItem(key);
    return JSON.parse(<string>ret);
  }
}

main.ts

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { StorageService } from './storage.service';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1>Hello from {{ name }}!</h1>
    <a target="_blank" href="https://angular.dev/overview">
      Learn more about Angular
    </a>
  `,
})
export class App {
  name = 'Angular';

  constructor(private storageService: StorageService) {}

  ngOnInit() {
    this.storageService.store('asdf', { test: 'qwerty' });
    setTimeout(() => {
      console.log(this.storageService.get('asdf'));
    }, 1000);
  }
}

bootstrapApplication(App);

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.