Error: Property 'token' does not exist on type 'Storage'

Error: Property 'token' does not exist on type 'Storage'

在离子前端的身份验证服务文件中,我试图通过构造函数体内的以下代码行从本地存储中获取令牌:

` constructor(private http: Http) {
    this.token = window.localStorage.token;
    if (this.token) {
      this.authorized = true;
    } else {
      this.authorized = false;
    }
  }`

我也在尝试在名为 setToken 的方法中设置令牌:

 setToken(token: string) {
    this.token = token;
    window.localStorage.token = this.token;
    this.authorized = true;
  }

但是,当我将鼠标悬停在 RHS 上的词标记上时,VS 代码在这两种情况下都显示错误消息。 Property 'token' does not exist on type 'Storage'我哪里做错了?

你没有正确使用本地存储,简而言之:

要保存数据,请使用代码:

localStorage.setItem("UNIQUE_NAME_ITEM", variable);

要检索某些项目,请使用代码:

localStorage.getItem("UNIQUE_NAME_ITEM")

此外,尝试检索尚未保存的项目时要小心,它会 return 为 null 或未定义。

希望对您有所帮助:)