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

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

Therefore, I need the current value of a Subject , which 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 to get current value from _panelOpened / panelOpened $?

Thanks.

+5
source share
2 answers

It seems that you are looking for a BehaviorSubject

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

If you subscribe, you will receive the last value as the first event.

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

Develop @MattBurnell in the comments on the accepted answer;

If you just need the current value right now (and you don't want a lot of subscribers floating around), you can simply use the getValue () method for 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 lead to:

 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 :

+2
source

Source: https://habr.com/ru/post/1245093/


All Articles