Typescript 获取角度服务中Subject.asObservable()的当前值

Typescript 获取角度服务中Subject.asObservable()的当前值,typescript,angular,rxjs,angular2-services,subject,Typescript,Angular,Rxjs,Angular2 Services,Subject,我想在Angular2服务中编写一个简单的切换 因此,我需要我观察到的对象的当前值(见下文) 从'angular2/core'导入{Injectable}; 从'rxjs/Subject'导入{Subject}; @可注射() 导出类设置服务{ private _panelOpened=新主题(); panelOpened$=此。\u panelOpened.asObservable(); 切换面板(){ this._panelOpened.next(!this.panelOpened$); }

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

因此,我需要我观察到的
对象的当前值(见下文)

从'angular2/core'导入{Injectable};
从'rxjs/Subject'导入{Subject};
@可注射()
导出类设置服务{
private _panelOpened=新主题();
panelOpened$=此。\u panelOpened.asObservable();
切换面板(){
this._panelOpened.next(!this.panelOpened$);
}
}
如何从_panelOpened/panelOpened$获取当前值


谢谢。

看来你在找


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

请参阅:

在这种情况下,主题或行为主题不应该重要。我知道如何订阅,但是没有订阅就没有办法获得价值吗?每次我只想要当前值时,订阅/取消订阅都会有点过载。。。在我看来,订阅更容易在值更改时收到通知。只需将最后一个值分配给本地字段。这很简单,您不需要。可观察的
不保留值。当它收到一个时,它将其转发给订阅者并丢弃它。一些特殊运算符和
BehaviorSubject
维护一个状态,但除了订阅之外,没有访问它的方法。BehaviorSubject实际上通过名为“getValue”的实例方法公开其当前值;无需订阅即可获得它。
private _panelOpened = new BehaviorSubject<boolean>(false);
togglePanel() {
  this.currentValue = !this.currentValue;
  this._panelOpened.next(this.currentValue);
}
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