我有以下代码
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 called on non-object
还有什么方法可以创建自定义类和使用的对象列表而不是在这里定义数组。
谢谢
最佳答案
是的,有一种方法可以做到。
首先声明一个类。
//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;
}
}
另一种方法是接口(interface)阅读一次文档- https://www.typescriptlang.org/docs/handbook/interfaces.html
也看看这个问题,很有意思-When to use Interface and Model in TypeScript / Angular2
关于angular - 在数组 angular 4 中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090080/