Search code examples
typescriptangularrxjsangular2-servicessubject

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


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.


Solution

  • 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);
    }