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