Angular 如何解决此错误后续属性声明必须具有相同的类型和重复的标识符。角度9

Angular 如何解决此错误后续属性声明必须具有相同的类型和重复的标识符。角度9,angular,compiler-errors,Angular,Compiler Errors,*我真的不知道也不明白为什么会发生这种情况,我是新使用Angular* 下面我将给出我的完整代码和完整错误 错误后续属性声明必须具有相同的类型。属性“post1”必须为“Posts”类型,但此处的类型为“any”和重复标识符“post1” 课程结束后 导出类帖子{ 键:字符串; 电子邮件:字符串; 密码:字符串; } AppComponent类,其中我使用了post类 导出类AppComponent{ 标题='项目-nro2'; post1=新的Posts(); //在每一篇博文中都提到了

*我真的不知道也不明白为什么会发生这种情况,我是新使用Angular*

  • 下面我将给出我的完整代码和完整错误
错误
后续属性声明必须具有相同的类型。属性“post1”必须为“Posts”类型,但此处的类型为“any”
和重复标识符“post1”

课程结束后

导出类帖子{
键:字符串;
电子邮件:字符串;
密码:字符串;
}
AppComponent类,其中我使用了
post类

导出类AppComponent{
标题='项目-nro2';
post1=新的Posts();
//在每一篇博文中都提到了上面的错误。
post1.Key='NONE';
post1.Email='NONE';
post1.密码='2';
}

属性不能直接在ES6中的类上初始化。在构造函数内初始化post对象并设置属性

export class AppComponent {
  title = 'proyecto-nro2';

  post1: Posts;

 constructor(){
  this.post1 = new Posts();
  this.post1.Key = 'NONE';
  this.post1.Email = 'NONE';
  this.post1.Password = '2';

 }
}
其他选项:

class Posts {
    Key: string;
    Email: string;
    Password: string;

    constructor(key: string, email: string, password: string) {
        this.Key = key;
        this.Email = email;
        this.Password = password;
    }
}

export class AppComponent {
  title = 'proyecto-nro2';
  post1: Posts = new Posts('NONE', 'NONE', '2');
}

正如@nayakam所说的,您应该在Posts对象的构造函数中设置属性

导出类帖子{
键:字符串;
电子邮件:字符串;
密码:字符串;
构造函数(键:字符串、电子邮件:字符串、密码:字符串){
this.key=key;
this.email=电子邮件;
this.password=密码;
}
}
这样做的问题是,如果某些参数是可选的,那么它可能会变得很烦人。对我来说,最好的语法是发送一个对象来初始化模型并导出一个接口,以便AppComponent知道Posts构造函数需要什么作为输入

导出接口ipost{
键:字符串;
电子邮件:字符串;
密码:字符串;
}
出口类职位{
键:字符串;
电子邮件:字符串;
密码:字符串;
构造函数(输入数据:IPosts){
this.key=inputData.key;
this.email=inputData.email;
this.password=inputData.password;
}
}
导出类AppComponent{
标题='项目-nro2';
职位1:职位=新职位({
关键字:“无”,
电子邮件:“无”,
密码:“2”
});
}