我创建了一个类模型,但我不知道如何用值来填充类。
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);
}
运行此命令时,用户仍然是空的。
您忘了添加变量并在构造函数中分配它们:
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;
}
}
添加访问说明符到构造函数参数以使其成为类属性。否则,它将仅被视为构造函数方法范围内的属性。
User.ts
export class User {
constructor(
public username: string,
public password: string,
public token: string
) { }
}
尝试这样:
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;
}
}