您好,我正在尝试创建一个新用户,但是这个语法不起作用 它说“用户”仅指一种类型,但在这里用作值。
onSubmit() {
if (this.userForm.valid) {
let user: User = new User(null,
this.userForm.controls['cin'].value,
this.userForm.controls['familyName'].value,
this.userForm.controls['givenName'].value,
this.userForm.controls['email'].value,
this.userForm.controls['description'].value,
this.userForm.controls['code'].value);
this.adminService.createUser(user).subscribe();
}
}
export interface User {
cin: string;
givenName: string;
familyName: string;
role: string;
id: string;
email: string;
}
这是因为 User 被声明为接口(interface)吗?我该如何解决? 提前致谢:)
最佳答案
是的,接口(interface)没有构造函数,它们只是告知编译器对象形状的类型,以便编译器可以检查你的代码并在编译时被删除。对我们来说,最简单的方法是使用对象字面量来创建满足接口(interface)的对象:
export interface User {
cin: string;
givenName: string;
familyName: string;
role: string;
id: string;
email: string;
}
let user: User = {
cin: this.userForm.controls['cin'].value,
familyName: this.userForm.controls['familyName'].value,
givenName: this.userForm.controls['givenName'].value,
email: this.userForm.controls['email'].value,
id : "", // not sure where this comes from
role: "" // not sure where this comes from
}
您也可以创建一个实现该接口(interface)的类,但如果您没有任何方法,通常不需要这样做。此外,您可能希望将某些字段标记为可选(例如 id,您可以这样使用:id?: string;
)
关于angular - 让用户 : User = new User (. ...) 为什么这对我不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447325/