获取 Angular 服务中 Subject.asObservable() 的当前值

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

我想在 Angular2 服务中编写一个简单的切换。

因此我需要我观察到的 Subject 的当前值(见下文)。

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

}

如何从 _panelOpened/panelOpened$ 获取当前值?

谢谢。

您似乎在寻找 BehaviorSubject

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

如果您订阅,您将获得最后一个值作为第一个事件。

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

在已接受答案的评论中详细说明@MattBurnell;

如果您现在只想要当前值(并且您不希望有很多订阅浮动),您可以只使用方法 getValue()行为主题。

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

这将导致:

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

参见plunker