繁体   English   中英

如何将对象附加到表中的现有对象中(角度2)

[英]How do I append an object into existing object in a table (Angular 2)

Empolyee类...

class Empolyee
public name: string;
public id: string;
public dep: string;

constructor(name, id, dep) {
   this.name = name;
   this.id = id;
   this.dep = dep;
}

打字稿

emp: Empolyee;
ngOnInit() {
     this.serviceA.getEmpolyee().subscribe( 
          { data => emp = data; });
}

addNew(newEmp) {
    this.emp = newEmp; //this does not work.... 
}

html

<table *ngFor="let person of emp">
    <tr>{{person.name}}</tr>
</table>

当我尝试此操作时,出现以下错误

ERROR Error: Error trying to diff 'Sam John'. Only arrays and iterables are allowed. 

那么如何将对象附加到emp? 还是有我没得到的东西? 我的目标是在表的前面添加新的员工并显示它。 不知何故我不明白为什么会引发错误。

这是调用getEmpolyee()返回的示例响应,返回以下内容。

  getEmpolyee() {
        return this.httpclient.get<Empolyee>('/getEmployee').map( data => data);
   }

从服务发送回的数据如下

"empolyee":[
{"name":"Reed Thomas","id":"5729","dep":"Sale"},
{"name":"Green Steve","id":"3268","dep":"IT"}
]

首先,您需要更改控制器中的变量

emp: Empolyee;

emp: Array<Empolyee>;

根据您提供的JSON模型,您可能需要在ngOnInit中执行以下操作

data => emp = data.empolyee;

addNew函数中,因此,您将使用数组取消移位函数:

this.emp.unshift(newEmp);

链接到其他完整示例: 员工角度代码

尝试这个:

 emp: Empolyee[]; ngOnInit() { this.serviceA.getEmpolyee().subscribe( data => this.emp = data.employee ); } addNew(newEmp) { this.emp.unshift(newEmp); } 

显然,您的服务仅返回一个Empolyee (顺便说一句,拼写不是吗?)。

因此,尝试这样做:

<table>
    <tr><td>{{emp.name}}</td></tr>
</table>

不过,这实际上是Angular的基础知识,因此您可能应该在某个地方修读教程/课程( 官方教程相当扎实)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM