In my component I have a save function like below:
save() {
var result;
//For updating task
if (this.task.AllTaskId) {
if (this.task.AssignedToCode == null) {
this.task.AssignedToCode = "All";
}
this.task.CreatedDate = new Date();
this.task.CreatedBy = this.empcode;
result = this._tasksService.updateTask(this.task).subscribe(
res => {
this._router.navigate(['/regtask'])
}
)
}
//For Adding new task
else {
if (this.task.AssignedToCode == null) {
this.task.AssignedToCode = "All";
}
this.task.CreatedDate = new Date();
this._tasksService.addTask(this.task)
.subscribe((ntask) => {
this.emitntask.emit(ntask);
this._router.navigate(['/regtask']);
this.temp = ntask.allTaskId;
console.log(this.temp);
})
debugger;
console.log(this.temp);
}
this.compform.reset();
}
If you look at the else condition of the save function, When I log the value temp in the .subscribe() function, it shows me the value in my log but when I try to log the same value outside the .subscribe() function, it shows me an undefined value like below:
Can anyone suggest me what to do and why 'this.temp' gets unavailable while it is available to me in .subscribe function?
Because it's asynchronous code. The second
console.log(this.temp)
actually occurs before the first one, because that one is wrapped in asubscribe()
call that only executes afteraddTask
completes (returns a value). The second one just executes immediately.That's because the callback you pass to
subscribe()
is run ASYNCHRONOUSLY.Try running the following code:
You will see this in the console:
The callback is run AFTER the code that comes right after
obs.subscribe()
.