可观察与主题和可观察 [英] Observable vs Subject and asObservable

查看:113
本文介绍了可观察与主题和可观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习RxJ,我正在根据自己的假设寻求确认或纠正.

我正在尝试使某个服务中的公开只读可见,我可以在我的服务类中的各个地方使用.next().我想知道这是否是正确的方法:

private myObservable = new Subject<T>();
public myObservable$: Observable<T> = this.myObservable.asObservable();

  • 用户可以订阅myObservable$
  • 我可以使用myObservable.next(...);

它工作得很好,但是我有足够的经验知道我可能只是个不知情的白痴(RxJS很大).这个用例的模式和对象正确吗?

解决方案

您所做的是正确的.但是,还有一种更短的表示法.由于Subject已经是一个Observable(它继承了Observable类),因此您可以将类型检查留给TypeScript:

private myObservable = new Subject<T>();
public myObservable$: Observable<T> = this.myObservable;

您的服务的任何使用者都可以订阅myObservable$,但无法调用myObservable$.next(),因为TypeScript不允许您这样做(Observable类没有任何next()方法).

这实际上是推荐的方法,RxJS在内部从不使用asObservable.有关更详细的讨论,请参见:

看到一个非常类似的问题:应该将rxjs主题在上课?

I am learning RxJs, I am seeking confirmation or correction on my assumption.

I am trying to make a public read only observable in a service that I can use .next() on in various places in my service class. I am wondering if this is the proper way to do it:

private myObservable = new Subject<T>();
public myObservable$: Observable<T> = this.myObservable.asObservable();

  • The user can subscribe to myObservable$
  • I can usemyObservable.next(...);

It works perfectly but I am experience enough to know that I may just be being an unwitting idiot (RxJS is huge). Is this correct pattern and correct object for said use case?

解决方案

What you're doing is correct. There's however still a little shorter notation. Since Subject is already an Observable (it inherits the Observable class) you can leave the type checking to TypeScript:

private myObservable = new Subject<T>();
public myObservable$: Observable<T> = this.myObservable;

Any consumer of your service can subscribe to myObservable$ but won't be able to call myObservable$.next() because TypeScript won't let you do that (Observable class doesn't have any next() method).

This is actually the recommended way of doing it and RxJS internally never uses asObservable anyway. For more detailed discussion see:

See a very similar question: Should rxjs subjects be public in the class?

这篇关于可观察与主题和可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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