11

我想在 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$ 获取当前值?

谢谢。

4

2 回答 2

13

似乎您正在寻找BehaviorSubject

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

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

togglePanel() {
  this.currentValue = !this.currentValue;
  this._panelOpened.next(this.currentValue);
}
于 2016-03-15T14:23:45.197 回答
4

在已接受答案的评论中详细说明@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

于 2017-06-05T10:27:39.527 回答