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

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

问题描述

如何在不订阅的情况下从 Observable 中获取当前值?我只想要一次当前值,而不是它们进来时的新值.

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.这意味着所有订阅者都会立即收到一个值(除非已经完成).

它将为您提供 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天全站免登陆