我有以下代码
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<{name: string, empoloyeeID: number}> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
console.log(this.name,this.empoloyeeID);
this.empList.push.apply(this.name,this.empoloyeeID);
this.name ="";
this.empoloyeeID = 0;
}
}
但是这个投掷错误
CreateListFromArrayLike调用非对象
还有什么方法可以创建自定义类和使用的对象列表,而不是在这里定义数组。
谢谢
发布于 2017-11-03 07:06:33
是有办法的。
先宣布一个类别。
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
然后在组件中导入类
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
另一种方法是将接口读入文档一次- https://www.typescriptlang.org/docs/handbook/interfaces.html
同时检查这个问题,这是非常有趣的- When to use Interface and Model in TypeScript / Angular2
发布于 2017-11-03 06:58:44
您的empList
是对象类型,但您正在尝试推送字符串。
尝尝这个
this.empList.push({this.name,this.empoloyeeID});
发布于 2017-11-03 07:00:15
将对象推到数组中。试试这个:
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<{name: string, empoloyeeID: number}> = [];
constructor() {}
ngOnInit() {}
onEmpCreate(){
console.log(this.name,this.empoloyeeID);
this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
this.name = "";
this.empoloyeeID = 0;
}
}
https://stackoverflow.com/questions/47090080
复制相似问题