Reputation: 3805
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
Upvotes: 1
Views: 142
Reputation: 7156
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
Upvotes: 2