服务的角度2值在订阅功能之外不可用 [英] Angular 2 value from service not available outside subscribe function
问题描述
在我的组件中,我具有以下保存功能:
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();
}
如果查看save函数的else条件,当我在.subscribe()函数中记录值temp时,它将向我显示日志中的值,但是当我尝试在.subscribe之外记录相同的值时()函数,它向我显示了一个未定义的值,如下所示:
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:
有人可以建议我怎么做,为什么.subscribe函数中的'this.temp'对我来说不可用?
Can anyone suggest me what to do and why 'this.temp' gets unavailable while it is available to me in .subscribe function?
推荐答案
这是因为传递给 subscribe()
的回调是 ASYNCHRONOUSLY .
That's because the callback you pass to subscribe()
is run ASYNCHRONOUSLY.
尝试运行以下代码:
// 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"
该回调将在 obs.subscribe()之后的代码 AFTER 之后运行.
The callback is run AFTER the code that comes right after obs.subscribe()
.
这篇关于服务的角度2值在订阅功能之外不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!