简体   繁体   English

如何在TypeScript / Angular中初始化类型化的对象?

[英]How to initialize a typed Object in TypeScript/Angular?

I'm new to Angular & TypeScript and trying to figure out how to instantiate an object (before an api request is returned with the real data). 我是Angular&TypeScript的新手,试图弄清楚如何实例化对象(在api请求返回真实数据之前)。

For example, my model looks like this: 例如,我的模型如下所示:

//order.model.ts
export class Order {
  constructor(public id: number, currency: string, public contact: Object, public items: Array<Object>) {}
}

And then I try to instantiate that in one of my components, let's say the App component: 然后,我尝试在我的一个组件中实例化该组件,比方说App组件:

//app.component.ts
export class AppComponent {
  @Input()
  public order: Order = new Order();
}

Of course, it expected to receive 4 arguments when instantiating new Order() but received 0. Do I actually have to pass in undefined/empty values for each attribute of Order? 当然,它在实例化new Order()时希望接收4个参数,但接收到0。实际上我是否必须为Order的每个属性传递未定义/空值?

In good ol' React (without TS) I would just initialize with an empty object and call it a day: 在良好的React中(不带TS),我将使用一个空对象进行初始化并将其命名为day:

this.state = {
 order: {}
}

What's best practice for this sort of thing in Angular/TS? 在Angular / TS中,这种事情的最佳实践是什么?

Yes as it is currently set up you would have to pass 4 default arguments to the constructor. 是的,因为当前已设置它,所以您必须将4个默认参数传递给构造函数。

public order: Order = new Order(1, '', {}, []); 公共秩序:Order = new Order(1,'',{},[]);

Or you can set each property as nullable by adding a ? 或者,您可以通过添加?将每个属性设置为可为空。 like so: 像这样:

export class Order {
  constructor(public id?: number, currency?: string, public contact?: Object, public items?: Array<Object>) {}
}

If the class doesn't have functionality (you are simply using it for type checking) the best way to do it would be to declare an interface like so (you can also make them nullable here with ?s): 如果该类没有功能(您只是在使用它进行类型检查),那么最好的方法是像这样声明一个接口(您也可以在此处用?s使其变为可空):

export interface Order {
    id: number;
    currency: string;
    contact: Object;
    items: Object[];
}

then in your component do not initialize the value until you have all of the needed values: 然后在您拥有所有必需的值之前,不要在组件中初始化该值:

//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;
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM