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.
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:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With