Reputation: 39
I have developed an Angular4 appln that calls a nodeExpressJS server to fetch JSON data and also adds data to the JSON object. The following is the onSubmit function of the addemployeeform.
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']);
}
But then it isn't pushing the id property to the JSON for newEmployee.
{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
is Aspirine.
And on uncommenting console.log(newEmployee.id );
line of code
I get a Nan error
Upvotes: 0
Views: 63
Reputation: 60518
First, shouldn't last
be defined as a number
and not any
?
Second, and more importantly, the lastEmployeeId call is most likely asynchronous, meaning it will not have completed before the next line of code is complete. You need to add all of the code that executes after that operation within the subscribe.
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)
);
And with that much code in the first function passed to your subscribe, you may want to instead make it it's own function:
this._employeeService.lastEmployeeID().subscribe(
(last: number) => this.processEmployeeId(last),
err => console.log(err));
processEmployeeId(last: number) {
// Your code here.
}
Upvotes: 1
Reputation: 14165
if last
is supposed to be a number type then state so:
let last: number;
If you're going to use typescript - you might as well use it to your advantage.
Upvotes: 0