Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular get方法在Typescript中返回未定义的_Angular_Typescript - Fatal编程技术网

Angular get方法在Typescript中返回未定义的

Angular get方法在Typescript中返回未定义的,angular,typescript,Angular,Typescript,在为私有字段定义get和set方法时,我不理解我的代码错误是什么 export class User{ private userName = "defaultName"; constructor(private token:string){} public get UserName():string{ return this.userName; } public set UserName(value:string){ this.use

在为私有字段定义get和set方法时,我不理解我的代码错误是什么

export class User{
  private userName = "defaultName";

  constructor(private token:string){}

  public get UserName():string{
    return this.userName;
  }

  public set UserName(value:string){
    this.userName = value;
  }    

  public get Token():string{
    return this.token;
  }

  public set Token(value:string){
    this.token= value;
  }
}
当我尝试下面的代码时,我得到了未定义的值

    const user:User = JSON.parse(localStorage.getItem("user"));
    console.log(user.UserName);
    console.log(user.Token);
编辑

问题不在于get方法。我尝试使用从localStorage检索的数据读取自定义对象(用户)的字段:

 const user:User = JSON.parse(localStorage.getItem("user"));
使用该代码,我可以使用get方法读取公共字段,但不能读取私有字段,因为当您解析
JSON.parse
数据(在我的例子中,从
localStorage
检索)时,您将获得一个普通的javascript对象,即使您尝试以这种方式“典型化”变量:
user:user

我尝试使用get方法
user.UserName
访问该字段,该方法实际上不存在于我用JSON.parse创建的普通javascript对象中;在这个普通javascript对象中,只有user.username字段。我想我尝试做的是不可能的。

那代码应该可以工作

你的例子为什么不奏效

当您从本地存储
用户
解析项时,变量变成如下所示:
{用户名:“John”,令牌:30}

但您访问的是不存在的
user.UserName
,因此您必须模拟
localStorage
中的对象,就像这样
user.UserName

解决方法:

  • 创建
    用户
    类的新实例
  • constuserfromloctorage=JSON.parse(JSON.stringify({userName:“John”,token:30}));
    const user=新用户(userFromLocalStorage.userName,userFromLocalStorage.token)
    console.log(user.userName);
    
    console.log(user.token)什么是
    用户
    ?请将此设置为a.Hi@kaya3,我编辑了您共享的代码,是否有结果或错误?关于创建示例?我不太明白这不是一个“可复制”的例子,因为它取决于您的本地存储中有什么,而这对于试图在我们自己的机器上复制问题的回答者来说是不存在的。这个问题实际上取决于使用本地存储吗?嗨,伙计们,我编辑了我的帖子,解释了为什么我不能做我想做的事情,因为这是“不合逻辑的”。嗨@Yuriy,谢谢你们的建议,我会按照它来做。我编辑了代码,问题似乎是另一个。