Angular 6 ES6启动对象数组

时间:2018-11-29 18:13:37

标签: javascript angular typescript class es6-class

我真的是javascript新手。

我有一个嵌套的类结构,需要在其中使用json对象进行初始化。我的问题是如何初始化EventDate对象数组并在CustomerEvents构造函数中分配给this.dates

   export default class CustomerEvent {
        constructor(customer_event: any) {
            this.event_title = customer_event.event_title;
            this.customer = customer_event.customer;
            this.total_budget = customer_event.total_budget;
            this.no_of_people = customer_event.no_of_people;
            this.dates = /**array of new EventDate(customer_event.dates) **/;
        }
        event_title: string;
        customer: Customer;
        total_budget: number;
        no_of_people: number;
        dates: EventDate[];

    }

    class EventDate {
        constructor(date: any) {
            this.start_date = date.start_date;
            this.end_date = date.end_date;
        }
        start_date: Date;
        end_date: Date;
    }

如果有人可以帮助我,那将真的很有帮助。谢谢

3 个答案:

答案 0 :(得分:1)

只需分配新的空数组,如下所示:

constructor(customer_event: any) {
  this.event_title = customer_event.event_title;
  this.customer = customer_event.customer;
  this.total_budget = customer_event.total_budget;
  this.no_of_people = customer_event.no_of_people;
  this.dates = [];
}

如果需要转换传入数组,可以执行以下操作:

...
this.dates = customer_event.dates.map(date => new EventDate(date));
...

答案 1 :(得分:1)

Angular Style Guide recommends使用interface s而不是class es进行数据模型:

  

考虑将接口用于数据模型。

话虽如此,您可以像这样重构代码:

export interface EventDate {
  start_date: Date;
  end_date: Date;
}

export interface CustomerEvent {
  event_title: string;
  customer: Customer;
  total_budget: number;
  no_of_people: number;
  dates: EventDate[];
}

现在,当涉及初始化时,您可以执行以下操作:

const customerEvent: CustomerEvent = {
  event_title: 'Some Title',
  customer: { /*An Object representing a Customer Type*/ }
  total_budget: 123,
  no_of_people: 456,
  dates: [{
    start_date: new Date(),
    end_date: new Date()
  }]
};

答案 2 :(得分:1)

自己创建这些实例:

constructor(customer_event: any) {
    this.event_title = customer_event.event_title;
    this.customer = customer_event.customer;
    this.total_budget = customer_event.total_budget;
    this.no_of_people = customer_event.no_of_people;
    this.dates = customer_event.dates.map(date => new EventDate(date));
}