1

How to Access Value Outside Subscribe Method

public ttl_count = 0;
ngOnInit() {
    this.MacService.getAllCouseCount().subscribe((res)=> {
        this.ttl_count = res['count']
    });
}

Whenever I console.log(this.ttl_count) within the subscribe function I get the right result but whenever I log it outside the subscribe function I get 0

Roman
  • 3,011
  • 2
  • 20
  • 30
Benson OO
  • 477
  • 5
  • 22
  • Because using `subscribe` makes the code asynchronous. Take a look at [this question](https://stackoverflow.com/questions/42039025/angular-2-value-from-service-not-available-outside-subscribe-function?rq=1). – Korfoo Apr 30 '19 at 08:19

2 Answers2

2

This is a known question. This is because of all the behavior of observable & subscribe is async, therefore it will have the value just after the subscription. So the functions should be fired after the sub.

public ttl_count=0;

ngOnInit()
{
  this.MacService.getAllCouseCount().subscribe((res)=>
   {
       this.ttl_count=res['count']; // <-- just here it gets the value.
       console.log(this.ttl_count); // <-- it has value, it happend after!

       this.example();
   });
  console.log(this.ttl_count); // <-- no value, it happend before.
}  

public example(): void 
{
    console.log(this.ttl_count); // <-- it has value here.
}
devDan
  • 5,969
  • 3
  • 21
  • 40
1

This is because this.MacService.getAllCouseCount().subscribe method is asynchronous and console.log(this.ttl_count) outside subscribe method executes first until you get the response from this.MacService.getAllCouseCount()

you could use async-await or convert this.MacService.getAllCouseCount() this to a promise.

Hans
  • 308
  • 7
  • 20