1

I am using subject which is emitting a value from one component. Then I subscribed it in another component and assigned it to a variable. The problem that I am facing is when I am printing the variable inside the subscribe function I'm able to see the value whereas It's showing default value when I am trying to print outside the subscribe function.

Can somebody explain the reason for this issue

Code

firstComponent

  this.dataService.activateMenusTab.next(false);

secondComponent

this.isMediaTabActive = true;
 this.dataService.activateMenusTab.subscribe((res) => {
      this.isMediaTabActive = res;
      console.log(this.isMediaTabActive);//printing false
    });
    console.log(this.isMediaTabActive);//printing true
ark
  • 3,707
  • 5
  • 21
  • 36
  • 2
    When you send an email, can you see the response from the receiver immediately after you've clicked the send button? No. The response is only visible later, when the receiver has read the email, and responded. Same here. That's why the service returns an Observable: to let you subscribe, in order to notify you when the response is finally available, long after the console.log() has been executed. – JB Nizet Jul 10 '18 at 14:04
  • In order to use the updated value, you have to do the processing inside of the `subscribe` callback. – ConnorsFan Jul 10 '18 at 14:28

1 Answers1

2

It's nothing but Sync and Async. That's why you are getting true as a value of this.isMediaTabActive outside the subscribe.

In the example, the this.isMediaTabActive = true; will be executed while the this.dataService.activateMenusTab is call to the service which will executed asynchronously. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.

Below I have mentioned the sequence of the line that will be executed.

1.    this.isMediaTabActive = true;
2.    this.dataService.activateMenusTab.subscribe((res) => {
4.       this.isMediaTabActive = res;
5.       console.log(this.isMediaTabActive);//printing false
      });
3.        console.log(this.isMediaTabActive);//printing true

For more info: Sync vs Async

Surjeet Bhadauriya
  • 6,755
  • 3
  • 34
  • 52
  • So What do I need to do so that after the subscribe function, The variable should have a value that I have set inside the subscribe – ark Jul 10 '18 at 14:17
  • No, you can't. The console.log statement after the subscribe will print the global value only as I already said in the answer. One patchy way to handle this is to make a function which will run on a set of an interval. And which checks for value change of this.isMediaTabActive. – Surjeet Bhadauriya Jul 10 '18 at 14:41
  • 1
    Ya I have solved the issue by removing subject and created a variable in service class and assigining value to it in one component and using it in another component and making it synchronous – ark Jul 10 '18 at 14:47