Nativescript-angular: How to set a variable from a subscription value that will be accessible in component class scope

114 Views Asked by At

I have an observable in my BottomNavigationService that returns the "current tab". The "current tab" is a Subject: private _currentTab: Subject<TabName> = new Subject<TabName>(); and the currentTab getter is an observable:

public get currentTab() {
  return this._currentTab.asObservable();
}

I am attempting to subscribe to this in a Component Page and set a variable local to that component class to use to check the current tab. This code:

console.log(`BEFORE SUBSCRIPTION: ${this._currentTabName}`);
this.bottomNavigationService.currentTab.subscribe(tabName => {
  this._currentTabName = tabName;
  console.log(`INSIDE SUBSCRIPTION: ${this._currentTabName}`);
});
console.log(`AFTER SUBSCRIPTION: ${this._currentTabName}`);

Is attempting to set a local _currentTabName variable (private _currentTabName: TabName;). The logs currently log:

  • INSIDE SUBSCRIPTION: homeTab
  • BEFORE SUBSCRIPTION: undefined
  • AFTER SUBSCRIPTION: undefined

What am I missing here to get this value into my component's local scope so I can use it?

1

There are 1 best solutions below

0
Mj.B On

Save the result of your this.bottomNavigationService.currentTab.subscribe in a variable that is in your component's scope.

export class <YOUR CLASS NAME> {
   navigationSubscription$: Subscription;
................
    navigationSubscription$ = this.bottomNavigationService.currentTab.subscribe(tabName => {
      this._currentTabName = tabName;
      console.log(`INSIDE SUBSCRIPTION: ${this._currentTabName}`);
    });
}

Now you can use navigationSubscription$ to access the subscription and unsubscribe it as well.