加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

以数组角度4添加项目

发布时间:2020-12-17 17:59:22 所属栏目:安全 来源:网络整理
导读:我有以下代码 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
我有以下代码

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

另一种方法是接口读取文档一次 – https://www.typescriptlang.org/docs/handbook/interfaces.html

结帐这个问题,非常有趣 – When to use Interface and Model in TypeScript / Angular2

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读