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

时间:2016-03-15 14:20:56

标签: typescript angular rxjs angular2-services subject

我想在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 $?

获取当前值

感谢。

2 个答案:

答案 0 :(得分:8)

似乎您正在寻找BehaviorSubject

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

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

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

答案 1 :(得分:3)

在接受的答案的评论中阐述@MattBurnell;

如果您现在只想要当前值(并且您不希望有大量订阅),您可以使用BehaviorSubject的 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