问题
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?
回答1:
Because it's asynchronous code. The second console.log(this.temp)
actually occurs before the first one, because that one is wrapped in a subscribe()
call that only executes after addTask
completes (returns a value). The second one just executes immediately.
回答2:
That's because the callback you pass to subscribe()
is run ASYNCHRONOUSLY.
Try running the following code:
// Some observable that takes a little while to complete (could be an HTTP request).
const obs = Observable.interval(200).first();
// Some callback that you want to execute when the obs emits/completes.
const callback = (val) => console.log('callback');
// Subscribe and log to console right after subscribing.
obs.subscribe(callback);
console.log('after subscribe');
You will see this in the console:
"after subscribe"
"callback"
The callback is run AFTER the code that comes right after obs.subscribe()
.
来源:https://stackoverflow.com/questions/42039025/angular-2-value-from-service-not-available-outside-subscribe-function