Angular 在本地存储器中将值转换为数字时为NaN

Angular 在本地存储器中将值转换为数字时为NaN,angular,angular7,angular7-router,Angular,Angular7,Angular7 Router,我在尝试从localStorage获取值时遇到NaN。有什么建议吗?在应用数字功能之前,该值为值“488” import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class PcUtilsService { constructor() { } // State Management setSession(key: string, value: any):

我在尝试从localStorage获取值时遇到NaN。有什么建议吗?在应用数字功能之前,该值为值“488”

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

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

  constructor() { }

  // State Management
  setSession(key: string, value: any): void {
    localStorage.setItem(key, JSON.stringify(value));
  }
  getSession(key: string): number {
    if (typeof window !== 'undefined') {
      const value = localStorage.getItem(key) as string;
      console.log('value', Number(value));
      return Number(value);
    }
  }

  clearSession(): void {
    localStorage.clear();
  }
}

由于在保存之前已经执行了
JSON.stringify(value)
,因此在检索时尝试将其转换为
Number
之前需要执行
JSON.parse(value)

因此,代码应该是这样的:
Number(JSON.parse(value))
如果值是
“488”
,它实际上是一个字符串。我还想通过删除
JSON.stringify
并使用
+
将字符串转换为数字来简化此过程,如下所示:

this.setSession('key','488');
// ...
设置会话(键:字符串,值:字符串):无效{
setItem(键、值);
常量a=+localStorage.getItem(键)
console.log(a)//现在是一个数字
}

您还可以发布“value”的值吗?是的,添加了,谢谢。我不知道为什么要将本地存储值作为字符串返回?当您从本地存储器访问该值时,默认情况下它不是字符串吗?