首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在数组角4中添加项

在数组角4中添加项
EN

Stack Overflow用户
提问于 2017-11-03 06:55:56
回答 3查看 280.4K关注 0票数 25

我有以下代码

代码语言:javascript
运行
复制
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调用非对象

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

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-11-03 07:06:33

是有办法的。

先宣布一个类别。

代码语言:javascript
运行
复制
//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

然后在组件中导入类

代码语言:javascript
运行
复制
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

票数 53
EN

Stack Overflow用户

发布于 2017-11-03 06:58:44

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

尝尝这个

代码语言:javascript
运行
复制
this.empList.push({this.name,this.empoloyeeID});
票数 13
EN

Stack Overflow用户

发布于 2017-11-03 07:00:15

将对象推到数组中。试试这个:

代码语言:javascript
运行
复制
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;
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47090080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档