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

查看:27
本文介绍了如何获取 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?

推荐答案

SubjectObservable 没有当前值.当一个值被发出时,它被传递给订阅者并且 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天全站免登陆