Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 293
Sommereder Avatar asked Mar 15 '16 14:03

Sommereder


2 Answers

To elaborate on @MattBurnell in the comments of the accepted answer;

If you just want the current value right now (and you don't want a lot of subscriptions floating around), you can just use the method getValue() of the BehaviorSubject.

import {Component, OnInit} from 'angular2/core';
import {BehaviorSubject} from 'rxjs/subject/BehaviorSubject';

@Component({
  selector: 'bs-test',
  template: '<p>Behaviour subject test</p>'
})
export class BsTest implements OnInit {

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

  ngOnInit() {
    console.log('initial value of _panelOpened', this._panelOpened.getValue());

    this._subscription = this._panelOpened.subscribe(next => {
      console.log('subscribing to it will work:', next);
    });

    // update the value:
    console.log('==== _panelOpened is now true ====');
    this._panelOpened.next(true);

    console.log('getValue will get the next value:', this._panelOpened.getValue());
  }
}

This will result in:

initial value of _panelOpened false
subscribing to it will work: false
==== _panelOpened is now true ====
subscribing to it will work: true
getValue will get the next value: true

See plunker:

like image 106
rnacken Avatar answered Oct 07 '22 07:10

rnacken


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);
}
like image 27
Günter Zöchbauer Avatar answered Oct 07 '22 06:10

Günter Zöchbauer