如何在Angular2和TypeScript中初始化数组

26

为什么 Angular2 和 Typescript 会出现这种情况?

export class Environment {
    constructor(
      id: string,
      name: string
    ) { }
}


 environments = new Environment('a','b');



app/environments/environment-form.component.ts(16,19): error TS2346: Supplied parameters do not match any signature of call target.

如何初始化一个数组?


2
你可以使用公共数据:Array<any> = []; - Ankit Pandey
6个回答

40
您可以使用这个结构:
export class AppComponent {

    title:string;
    myHero:string;
    heroes: any[];

    constructor() {
       this.title = 'Tour of Heros';
       this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
       this.myHero = this.heroes[0];
    }
}

23

你可以像这样创建和初始化任何对象的数组。

hero:Hero[]=[];

我该如何将 hero 设置为大小为5? - JackSlayer94
在声明数组时进行初始化是最佳实践吗?还是应该在构造函数或ngOnInit()中进行初始化? - Patrick

10

类定义应该像这样:

export class Environment {
    cId:string;
    cName:string;

    constructor( id: string, name: string ) { 
        this.cId = id;
        this.cName = name;
    }

    getMyFields(){
        return this.cId + " " + this.cName;
    }
}

 var environments = new Environment('a','b');
 console.log(environments.getMyFields()); // will print a b

来源: https://www.typescriptlang.org/docs/handbook/classes.html


4
我不完全理解你所说的“初始化数组”的真正含义是什么?
以下是一个例子:
class Environment {

    // you can declare private, public and protected variables in constructor signature 
    constructor(
        private id: string,
        private name: string
    ) { 
        alert( this.id );
    }
}


let environments = new Environment('a','b');

// creating and initializing array of Environment objects
let envArr: Array<Environment> = [ 
        new Environment('c','v'), 
        new Environment('c','v'), 
        new Environment('g','g'), 
        new Environment('3','e') 
  ];

在此尝试:https://www.typescriptlang.org/play/index.html

0

嗨@JackSlayer94,请查看以下示例以了解如何创建大小为5的数组。

class Hero {
    name: string;
    constructor(text: string) {
        this.name = text;
    }

    display() {
        return "Hello, " + this.name;
    }

}

let heros:Hero[] = new Array(5);
for (let i = 0; i < 5; i++){
    heros[i] = new Hero("Name: " + i);
}

for (let i = 0; i < 5; i++){
    console.log(heros[i].display());
}


0
为了更加简洁,您可以将构造函数参数声明为public,这将自动创建具有相同名称的属性,并且这些属性可以通过this访问:
export class Environment {

  constructor(public id:number, public name:string) {}

  getProperties() {
    return `${this.id} : ${this.name}`;
  }
}

let serverEnv = new Environment(80, 'port');
console.log(serverEnv);

 ---result---
// Environment { id: 80, name: 'port' }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接