gpt4 book ai didi

javascript - 为 JSON 属性抛出 Nan 消息

转载 作者:行者123 更新时间:2023-12-03 02:24:22 26 4
gpt4 key购买 nike

我开发了一个 Angular4 应用程序,它调用 nodeExpressJS 服务器来获取 JSON 数据,并将数据添加到 JSON 对象。以下是addemployeeform的onSubmit函数。

onSubmit(formValue: any) {
console.log("Form Value = " + JSON.stringify(formValue, null, 4));
let newEmployee: Emp;
let last: any;
this._employeeService.lastEmployeeID().subscribe((last: any) => last = last,
err => console.log(err));
newEmployee = {
//id: employeeCount + 1,
id: last + 1,
name: formValue.name,
manufacturer: formValue.manufacturer,
type: formValue.type,
batchno: formValue.batchno,
expdate: formValue.expdate,
price: formValue.price
};
// console.log(newEmployee.id );
let temp = this._employeeService.addEmployee(newEmployee).subscribe(err =>
console.log(err));
this.router.navigate(['employees']);
}

但是它不会将 id 属性推送到 newEmployee 的 JSON。

{id: 1, name: "Paracetamol", manufacturer: "Ranbaxy", type: "Tablet", batchno …}

{id: 2, name: "Sinarest", manufacturer: "GSK", type: "Tablet", batchno: …}

{id: 3, name: "Viagra", manufacturer: "Pfizer", type: "Capsule", batchno: …}

{name: "Aspirine", manufacturer: "Aspirine", type: "Syrup", batchno: "03/46", expdate: "03/04/2023", …}

newEmployee 是阿司匹林。

并取消注释 console.log(newEmployee.id ); 代码行

我收到 Nan 错误

最佳答案

首先,last 不应该被定义为 number 而不是 any 吗?

其次,更重要的是,lastEmployeeId 调用很可能是异步的,这意味着在下一行代码完成之前它不会完成。您需要在订阅中添加在该操作之后执行的所有代码。

this._employeeService.lastEmployeeID().subscribe(
(last: any) => {
last = last;
newEmployee = {
//id: employeeCount + 1,
id: last + 1,
name: formValue.name,
manufacturer: formValue.manufacturer,
type: formValue.type,
batchno: formValue.batchno,
expdate: formValue.expdate,
price: formValue.price
};
// console.log(newEmployee.id );
let temp = this._employeeService.addEmployee(newEmployee).subscribe(
employee => {
console.log(employee);
this.router.navigate(['employees']);
},
err => console.log(err)
);

第一个函数中的这么多代码传递给您的订阅,您可能希望将其设为自己的函数:

this._employeeService.lastEmployeeID().subscribe(
(last: number) => this.processEmployeeId(last),
err => console.log(err));

processEmployeeId(last: number) {
// Your code here.
}

关于javascript - 为 JSON 属性抛出 Nan 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com