如何获取RxJS Subject或Observable的当前值? [英] How to get current value of RxJS Subject or Observable?

查看:97
本文介绍了如何获取RxJS Subject或Observable的当前值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular 2服务:

I have an Angular 2 service:

import {Storage} from './storage';
import {Injectable} from 'angular2/core';
import {Subject}    from 'rxjs/Subject';

@Injectable()
export class SessionStorage extends Storage {
  private _isLoggedInSource = new Subject<boolean>();
  isLoggedIn = this._isLoggedInSource.asObservable();
  constructor() {
    super('session');
  }
  setIsLoggedIn(value: boolean) {
    this.setItem('_isLoggedIn', value, () => {
      this._isLoggedInSource.next(value);
    });
  }
}

一切都很好。但我有另一个不需要订阅的组件,它只需要在某个时间点获取isLoggedIn的当前值。我该怎么做?

Everything works great. But I have another component which doesn't need to subscribe, it just needs to get the current value of isLoggedIn at a certain point in time. How can I do this?

推荐答案

A 主题 Observable 没有当前值。当一个值被发出时,它被传递给订阅者并且 Observable 就完成了。

A Subject or Observable doesn't have a current value. When a value is emitted, it is passed to subscribers and the Observable is done with it.

如果你想要要获得当前值,请使用 BehaviorSubject ,这是为了这个目的而设计的。 BehaviorSubject 保留最后一次发出的值,并立即将其发送给新订阅者。

If you want to have a current value, use BehaviorSubject which is designed for exactly that purpose. BehaviorSubject keeps the last emitted value and emits it immediately to new subscribers.

它还有一个方法 getValue()获取当前值。

It also has a method getValue() to get the current value.

这篇关于如何获取RxJS Subject或Observable的当前值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆