2016-06-11 33 views
13

为什么在Angular2和Typescript中发生这种情况?如何在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. 

如何初始化数组?

+0

可以使用公共数据:数组 = []; –

回答

4

类的定义应该是这样的:

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

1

我不完全是你真正通过初始化数组是什么意思?

下面是一个例子

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

为了使更简洁,你可以声明构造函数的参数为​​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' } 
32

你可以使用这个构造:

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]; 
    } 
} 
6

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

hero:Hero[]=[]; 
+0

我如何设置'英雄'为5的大小? – JackSlayer94

+1

**在相同的线程中查看下面的帖子中的答案** –

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