如何获取 RxJS Subject 或 Observable 的当前值?

328

我有一个 Angular 2 的服务:

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的当前值。我该怎么做?

13个回答

0

另一种方法,如果您想/能够使用async await(必须在异步函数内部),您可以使用现代Rxjs进行操作:

 async myFunction () {
     const currentValue = await firstValueFrom(
      of(0).pipe(
        withLatestFrom(this.yourObservable$),
        map((tuple) => tuple[1]),
        take(1)
      )
    );
    // do stuff with current value

 }

 

由于使用了withLatestFrom,这将立即发出一个值"Right away",然后将解决该Promise。


0

最好的方法是使用 BehaviorSubject,以下是一个例子:

var sub = new rxjs.BehaviorSubject([0, 1])
sub.next([2, 3])
setTimeout(() => {sub.next([4, 5])}, 1500)
sub.subscribe(a => console.log(a)) //2, 3 (current value) -> wait 2 sec -> 4, 5

0
Observables只是函数。它们返回一系列的值,但是为了看到这些值,你需要订阅它们。最基本的方法是在observable上调用subscribe()方法,并传入一个观察者next()回调作为参数。
另外,你还可以使用Subscriber,它是Observer的一种实现,但提供了额外的功能,比如unsubscribe
import { Subscription } from 'rxjs';

export class SessionStorage extends Storage {
  private _isLoggedInSource = new Subject<boolean>();
  privat _subs = new Subscription();
  isLoggedIn$ = this._isLoggedInSource.asObservable();
  isLoggedIn = false;
  constructor() {
    super('session');
    this._subs.add(this.isLoggedIn$.subscribe((value) => this.isLoggedIn = v))
  }
  setIsLoggedIn(value: boolean) {
    this.setItem('_isLoggedIn', value, () => {
      this._isLoggedInSource.next(value);
    });
  }
}

然后在另一个组件中,您可以导入SessionStorage并访问isLoggedIn的值。 注意:我会使用new Observable()构造函数将_isLoggedInSource的数据封装在一个可观察对象中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接