无需订阅即可从Observable获取当前值(只需一次获得所需值)

编程入门 行业动态 更新时间:2024-10-24 14:19:58
本文介绍了无需订阅即可从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提供一个名为value的getter属性,以获取通过它的最新值.

      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获取当前值(只需一次获得所需值)

本文发布于:2023-11-28 22:46:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644246.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:只需   所需   Observable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!