Md.*_*lam 7 typescript angular
我有以下代码
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但这个投掷错误
CreateListFromArrayLike在非对象上调用
还有什么方法可以创建自定义类和使用的对象列表,而不是在这里定义数组.
谢谢
Sri*_*kar 17
是的,有办法做到这一点.
首先声明一个类.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Run Code Online (Sandbox Code Playgroud)
然后在您的组件中导入该类
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;
}
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是接口读取文档一次 - https://www.typescriptlang.org/docs/handbook/interfaces.html
结帐这个问题,非常有趣 - 何时在TypeScript/Angular2中使用Interface和Model
您empList是对象类型,但您正在尝试推送字符串
尝试这个
this.empList.push({this.name,this.empoloyeeID});
Run Code Online (Sandbox Code Playgroud)
将对象推入您的数组。尝试这个:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91425 次 |
| 最近记录: |