服务中的Angular 2值在订阅功能之外不可用

时间:2017-02-04 10:03:13

标签: angular subscribe

在我的组件中,我有一个如下所示的保存功能:

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之外记录相同的值时()函数,它显示了一个未定义的值,如下所示:

enter image description here

任何人都可以建议我做什么以及为什么'this.temp'在.subscribe函数中可用时无法使用?

2 个答案:

答案 0 :(得分:2)

这是因为您传递给subscribe()的回调是异步

尝试运行以下代码:

// 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');

您将在控制台中看到此内容:

"after subscribe"
"callback"

回调是在obs.subscribe()之后的之后运行

答案 1 :(得分:2)

因为它是异步代码。第二个console.log(this.temp)实际上发生在之前第一个,因为那个subscribe()包含在addTask调用中,只在class A { public $status; public function __construct(){} } class B extends A { public $status; public function __construct(){} public function modifyParentStatus(){ /* In the next line i want to change the parent class variable But it changes the current class variable */ $this->status = 'active'; } } $obj = new B(); $obj->modifyParentStatus(); 完成后执行(返回一个值)。第二个就是立即执行。