首页 > 解决方案 > How to access value outside the .subscribe in angular 2 polling service

问题描述

// I was trying to get the values from outside the subscribe but it cannot assign to any variable. In my project, get the json content using http.post() method and assigned it to a variable. I want to access these variable value outside the constructor ..How can I make it possible ?

ngOnInit(): void {
    this.getSubscription();
}

// here is my subscription function

getSubscription() {
    interval(5000)
        .pipe(
         startWith(0),
         switchMap(() => this._subscriptionService.getSubData()))
         .subscribe(data => {
             this.Result = data; // able to print the data
             JSON.stringify(this.Result);

             console.log(this.Result); // able to print the data
         });

    console.log(this.Result); // undefined is printing                
}

// I want to access this.result outside the subscribe and assigned to a public variable

标签: angularpollingsubscribe

解决方案


您正在调用getSubscription()内部ngOnInit,并且在执行时您的变量Result未设置,因为您的 http 请求是异步的。在您的订阅方法第一次执行后,变量被设置。

如果其他函数需要该值,我建议您在订阅中调用它们,否则您无法确定您的 http 请求何时完成。

getSubscription() {
    interval(5000)
        .pipe(
         startWith(0),
         switchMap(() => this._subscriptionService.getSubData()))
         .subscribe(data => {
             this.Result = data; // able to print the data
             JSON.stringify(this.Result);

             console.log(this.Result); // able to print the data

             // Is called every time you get a new result and this.Result is set now
             this.processResults();
     });

    // Not set yet
    console.log(this.Result); // undefined is printing                
}

processResults() {
    // Do some stuff with your results, this.Result is set now
}

推荐阅读