简体   繁体   English

类构造函数angular 2的默认数组值

[英]Default array value to class constructor angular 2

class DateComponent {
  constructor(public months:string[] = [],public days:number[] = [] , public years:number[] = []) { }

};

This is giving me error in Chrome. 这给我在Chrome中的错误。 Says "=" is invalid. 说“ =”无效。 I am using angular 2 and typescript and webpack dev server. 我正在使用angular 2和typescript和webpack开发服务器。

How can i pass values to the parameters in constructor? 如何将值传递给构造函数中的参数?

Like Harry says in the comment, defining class members in the constructor is reserved for dependency injection in Angular 2. 就像哈里在评论中说的那样,在构造函数中定义类成员保留用于Angular 2中的依赖项注入。

I'd suggest moving those out of the constructor: 我建议将它们移出构造函数:

class DateComponent {
  public months: Array<string> = [];
  public days: Array<string> = [];
  public years: Array<string> = [];

  constructor() { 

  }
}

if you want optional parameter of constructor you must add "?". 如果要使用构造函数的可选参数,则必须添加“?”。 But the parameter of the object must define out of constructor. 但是对象的参数必须在构造函数之外定义。

In angular2 u will see that some parameter define in constructor but this have use in annotation (@Component, @Directive,...) that's define there as class property. 在angular2中,您会看到一些在构造函数中定义的参数,但已在其中定义为类属性的注释(@ Component,@ Directive等)中使用。

if i understand correct you want something like this: 如果我理解正确,那么您想要这样的事情:

class DateComponent {
      public months: [] = [];
      public days: [] = [];
      public years: [] = [];

      constructor(_months?:string[],_days?:number[], _years?:number[]) {
       this.months = _months;
       this.days = _days;
       this.years = _years;
     }

    };

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

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