Search code examples
angularpollingsubscribe

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


Solution

  • You're calling the getSubscription() within ngOnInit and at this point of execution your variable Result is not set, because your http request asynchronus. After the first execution of your subscribe-method the variable is set.

    If the value is required in other functions I suggest you to call them from within your subscribe, because otherwise you cannot be sure when your http-request is finished.

    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
    }