如何以角形填充打字稿类模型

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

我创建了一个类模型,但我不知道如何用值来填充类。

User.ts

export class User {
    constructor(
        username: string,
        password: string,
        token: string
    ) { }
}

app.component.ts

  ngOnInit() {

    let user = new User('uname' , 'pword', 'sampletoken');
    console.log(user);
  }

运行此命令时,用户仍然是空的。

enter image description here

angular
2个回答
1
投票

您忘了添加变量并在构造函数中分配它们:

export class User {
    username: string;
    password: string;
    token: string;

    constructor(username: string,
                password: string,
                token: string) {
         this.username = username;
         this.password= password;
         this.token= token;
    }
}

1
投票

添加访问说明符到构造函数参数以使其成为类属性。否则,它将仅被视为构造函数方法范围内的属性。

User.ts

export class User {
    constructor(
        public username: string,
        public password: string,
        public token: string
    ) { }
}

1
投票

尝试这样:

export class User {
  username: string;
  password: string;
  token: string;
  constructor(username: string, password: string, token: string) {
    this.username = username;
    this.password = password; 
    this.token = token;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.