2016-06-11 36 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()); 
 
}