Get current value of Subject.asObservable() inside Angular service

Sommereder picture Sommereder · Mar 15, 2016 · Viewed 25.7k times · Source

I want to write a simple toggle inside an Angular2 service.

Therefore I need the current value of a Subject I observe (see below).

import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';

@Injectable()

export class SettingsService {

  private _panelOpened = new Subject<boolean>();
  panelOpened$ = this._panelOpened.asObservable();

  togglePanel() {
    this._panelOpened.next(!this.panelOpened$);
  }

}

How do I get the current value from _panelOpened/panelOpened$?

Thanks.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Mar 15, 2016

Seems you are looking for BehaviorSubject

private _panelOpened = new BehaviorSubject<boolean>(false);

If you subscribe you get the last value as first event.

togglePanel() {
  this.currentValue = !this.currentValue;
  this._panelOpened.next(this.currentValue);
}