以数组角度4添加项目

时间:2017-11-03 06:55:57

标签: angular typescript

我有以下代码

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

还有什么方法可以创建自定义类和使用过的对象列表,而不是在这里定义数组。

由于

3 个答案:

答案 0 :(得分:12)

是的,有办法做到这一点。

首先宣布一个班级。

//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

答案 1 :(得分:3)

您的empList是对象类型,但您正在尝试推送字符串

试试这个

this.empList.push({this.name,this.empoloyeeID});

答案 2 :(得分:2)

将对象推入数组。试试这个:

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;
    }
}