angular - 如何解决错误后续属性声明必须具有相同的类型。角 9
问题描述
我创建了一个类型的类,Posts
它具有三个字符串类型的字段,我正在尝试从 Angular 组件类访问它以将三个字段设置为其默认值,但出现以下错误...
Subsequent property declarations must have the same type.
Property 'post1' must be of type 'Posts', but here has type 'any'
我的Posts
班级代码
export class Posts{
Key:string;
Email:string;
Password:string;
}
我如何尝试在 Angular 组件类中设置值的代码
export class AppComponent {
title = 'proyecto-nro2';
post1 = new Posts();
//Said the error above in every post1.
post1.Key = 'NONE';
post1.Email = 'NONE';
post1.Password = '2';
}
解决方案
你可以...
1)Posts
在类中添加一个构造函数,以便在使用new
. 在构造函数中使用public
访问器将自动将参数声明为可公开访问的属性。
export class Posts {
constructor(
public key: string,
public email: string,
public password: string,
) { }
}
export class AppComponent {
// order of the parameters matters here
// as it matches the order in the class constructor
post1 = new Post('NONE', 'NONE', '2');
}
2)在AppComponent
您可以简单地将类型分配Posts
给您的属性并分配值而不使用new
.
export class Posts {
key: string;
email: string;
password: string;
}
export class AppComponent {
// order of the properties doesn't matter here
// as long as the properties exist and match the type
post1: Posts = {
key: 'NONE',
email: 'NONE',
password: '2',
};
}
如果必须动态分配对象的值,则必须在函数内部完成。
export class Posts {
key: string;
email: string;
password: string;
}
export class AppComponent implements OnInit {
post1 = new Posts();
ngOnInit() {
post1.key = 'NONE';
post1.email = 'NONE';
post1.password = '2';
}
}
推荐阅读
- python - 如何从元素中提取链接?
- cordova - 如何使用 cordova.inAppBrower 禁用全屏视图
- c++ - 模板化构造函数无法执行转换
- python - 并排绘制多个不同大小的列表?
- javascript - 如何重新排列 WordPress REST API 评论?
- node.js - Redux-Form 字段仅出现在输入底部的一行而不是框。有没有办法拿到盒子?
- ios - 使 UIAccessibilityTrait 可调整忽略双击(如按钮)迅速
- arrays - 如何从 CoreData TableView 数组中提取 Data Array,将其放入新的 Array 并将其导出为 csv?
- android - 如何优雅地处理 sigaction() 并回馈父进程
- apiblueprint - 使用 V4 交互式文档在本地渲染养蜂场文档