You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular StorageService存入localStorage成功但无法取值问题

Angular Storage服务无法检索值的问题修复

问题根源

你的store方法逻辑完全错误:

  • 当前代码是把传入的storageKey存在固定键名'key'下,把value存在固定键名'value'下,而非用传入的storageKey作为键来关联对应的值。
  • 这就导致调用get('userData')时,localStorage中根本不存在userData这个键,返回null;调用get('key')时,取到的是字符串'userData',直接JSON.parse会因为非JSON格式报错。

修正后的代码

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

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

  // 存储值:用传入的storageKey作为键,存储序列化后的value
  async store(storageKey: string, value: any) {
    // localStorage仅支持字符串存储,需先序列化对象
    localStorage.setItem(storageKey, JSON.stringify(value));
  }
  
  // 获取值:先判断存在性再解析,避免报错
  async get(key: string) {
    const ret = localStorage.getItem(key);
    return ret ? JSON.parse(ret) : null;
  } 
}

关键修正说明

  1. 存储逻辑:直接使用传入的storageKey作为localStorage的键,同时通过JSON.stringify()将任意类型的value转换为字符串,适配localStorage的存储限制。
  2. 获取逻辑:增加空值判断,当ret为null时直接返回null,避免JSON.parse(null)抛出语法错误。

内容的提问来源于stack exchange,提问作者techwestcoastsfosea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:49:51