如何在angular2和typescript中初始化数组

Tam*_*mpa 20 typescript angular

为什么会在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.
Run Code Online (Sandbox Code Playgroud)

如何初始化数组?

小智 39

你可以使用这个结构:

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];
    }
}
Run Code Online (Sandbox Code Playgroud)


Mah*_*dav 17

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

hero:Hero[]=[];
Run Code Online (Sandbox Code Playgroud)

  • **在下面的帖子中查看同一帖子中的答案** (2认同)

eko*_*eko 9

类定义应该是这样的:

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
Run Code Online (Sandbox Code Playgroud)

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