您好我正在尝试创建新用户,此语法不起作用 它说'用户'只引用一种类型,但在这里被用作一个值。
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被声明为接口?我怎么解决它? 在此先感谢:)
答案 0 :(得分:5)
是的,接口没有构造函数,它们只是通知编译器有关对象形状的类型,因此编译器可以检查代码并在编译时擦除。最简单的方法是给我们一个对象文字来创建一个满足接口的对象:
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
}
您还可以创建一个实现该界面的类,但如果您没有任何方法,通常不需要这样做。此外,您可能希望将某些字段标记为可选(例如id,您可以使用以下方式执行此操作:id?: string;
)
答案 1 :(得分:3)
如果您使用关键字class
interface
代替new
export class User {
cin: string;
givenName: string;
familyName: string;
role: string;
id: string;
email: string;
}
答案 2 :(得分:1)
let user = <User>{
// properties of User interface
};