3

// 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

Batajus
  • 5,831
  • 3
  • 25
  • 38
Nuwan Bandara
  • 35
  • 1
  • 1
  • 6

3 Answers3

4

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
}
Batajus
  • 5,831
  • 3
  • 25
  • 38
0

define Result outside the function like below

Result:any;

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                
          }
prady
  • 416
  • 2
  • 6
  • 17
-1

It is happening because console.log(this.Result) executes before .subscribe() method finishes it's execution. This can be handled by using async await.

async ngOnInit(): void {
 await this.getSubscription();
}
Darshan Bhavsar
  • 169
  • 1
  • 4