我开发了一个Angular4基本CRUD应用程序,它与nodejs后端API交互,后端API呈现JSON数组的数据。但是在使用.push()方法向JSON数组添加对象时,它会将最后一个对象替换为要添加的新对象,而不是将其推送到数组。
以下是员工的定义:
export interface Employee {
id:number,
name:string,
review:string[],
peers:string[]
}
服务方法使HTTP调用如下:
addEmployee(addedEmployee:Employee):Observable<Response>
{
return
this._http.post("http://localhost:3001/add",addedEmployee)
.pipe(catchError(this.handleError));
}
将一个Employee对象添加到JSON对象数组的后端API代码如下:
app.post('/add',function(req,res){
var addedEmployee={};
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
employees.push(addedEmployee);
console.log('added');
res.json(employees);
})
后端JSON对象数组的before,intermediate和after结构如下:
在:
employees = [
{
id: 1,
name: "John Doe",
review: ["Hardworking"],
peers: ["admin", "Matt"]
},
{
id: 2,
name: "Matt Hofner",
review: ["Hardworking"],
peers: ["admin"]
},
{
id: 3,
name: "Judy Ruth",
review: ["Focused"],
peers: ["admin", "Matt"]
}
];
中间体:
let addedEmployee:Employee = {
id: 4,
name: "Trudy",
review:["Lazy"],
peers: ["Matt"]
};
决赛:
employees = [
{
id: 1,
name: "John Doe",
review: ["Hardworking"],
peers: ["admin", "Matt"]
},
{
id: 2,
name: "Matt Hofner",
review: ["Hardworking"],
peers: ["admin"]
},
{
id: 4,
name: "Trudy",
review: ["Lazy"],
peers: ["Matt"]
}
];
答案 0 :(得分:0)
这很奇怪。这可能不是最佳解决方案,但请尝试使用.concat()方法:
app.post('/add',function(req,res){
var addedEmployee={};
var singleEmployeeArray = [];
addedEmployee.id=req.body.id;
addedEmployee.name=req.body.name;
addedEmployee.review=req.body.review;
addedEmployee.peers=req.body.peers;
singleEmployeeArray.push(addedEmployee);
employees.concat(singleNewEmployeeArray);
console.log('added');
res.json(employees);
})