我是Angular和TypeScript的新手,并试图弄清楚如何实例化一个对象(在使用真实数据返回api请求之前)。
例如,我的模型如下所示:
//order.model.ts
export class Order {
constructor(public id: number, currency: string, public contact: Object, public items: Array<Object>) {}
}
然后我尝试在我的一个组件中实例化,让我们说App组件:
//app.component.ts
export class AppComponent {
@Input()
public order: Order = new Order();
}
当然,它预计在实例化new Order()
但收到0时会收到4个参数。我实际上必须为Order的每个属性传递未定义/空值吗?
在好的'React(没有TS)中,我只想用一个空对象初始化并称之为一天:
this.state = {
order: {}
}
在Angular / TS中这种事情的最佳实践是什么?
是的,因为它当前已设置,您必须将4个默认参数传递给构造函数。
公共秩序:Order = new Order(1,'',{},[]);
或者您可以通过添加?将每个属性设置为可为空?像这样:
export class Order {
constructor(public id?: number, currency?: string, public contact?: Object, public items?: Array<Object>) {}
}
如果类没有功能(你只是用它来进行类型检查),那么最好的方法就是声明一个这样的接口(你也可以在这里使用?s)使它们可以为空:
export interface Order {
id: number;
currency: string;
contact: Object;
items: Object[];
}
然后在您的组件中,在您拥有所有需要的值之前不要初始化该值:
//app.component.ts
export class AppComponent {
@Input()
public order: Order;
// just an example
setValues(id: number, currency: string, contact: Object, items: Object[]) {
this.order = {
id: id,
currency: currency,
contact: contact,
items: items
}
}
// example for if you receive object with correct fields from backend
getData() {
this.service.getData().subscribe(result => {
this.order = result;
});
}
}