无需订阅即可从Observable获取当前值(只需一次获得所需值) [英] Get current value from Observable without subscribing (just want value one time)

查看:554
本文介绍了无需订阅即可从Observable获取当前值(只需一次获得所需值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切.如何在不订阅的情况下从Observable获取当前值?我只希望当前值一次而不是新值,因为它们会传入...

The title says it all really. How can I get the current value from an Observable without subscribing to it? I just want the current value one time and not new values as they are coming in...

推荐答案

您需要使用 BehaviorSubject

  • BehaviorSubject与ReplaySubject相似,只不过它只记住最后一个发布.
  • BehaviorSubject还要求您提供默认值T.这意味着所有订阅者都将立即收到一个值. (除非它已经完成).
  • BehaviorSubject is similar to ReplaySubject except it only remembers the last publication.
  • BehaviorSubject also requires you to provide it a default value of T. This means that all subscribers will receive a value immediately (unless it is already completed).

它将为您提供Observable发布的最新值.

It will give you the most recent value published by the Observable.

BehaviorSubject提供一个名为valuegetter属性,以获取通过它的最新值.

BehaviorSubject provides a getter property named value to get the most recent value passed through it.

StackBlitz

  • 在此示例中,将值"a"写入控制台:

//Declare a Subject, you'll need to provide a default value.
const subject: BehaviorSubject<string> = new BehaviorSubject("a");

用法:

console.log(subject.value); // will print the current value


隐藏主题并仅公开其值

如果您想隐藏BehaviorSubject并仅公开其值(例如,从Service进行访问),则可以使用这样的getter.


Conceal the Subject and only expose it's value

In case you want to conceal your BehaviorSubject and only expose it's value, let's say from a Service, you can use a getter like this.

export class YourService {
  private subject = new BehaviorSubject('random');

  public get subjectValue() {
    return this.subject.value;
  }
}

这篇关于无需订阅即可从Observable获取当前值(只需一次获得所需值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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