为什么会在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 :(得分: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];
}
}
答案 1 :(得分:16)
你可以像这样创建和初始化任何对象的数组。
hero:Hero[]=[];
答案 2 :(得分:8)
类定义应该是:
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
答案 3 :(得分:2)
我不完全明白初始化数组的真正含义是什么?
以下是一个例子:
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')
];
答案 4 :(得分: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' }
答案 5 :(得分:0)
hi @ 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());
}