Observable vs Subject 和 asObservable [英] Observable vs Subject and asObservable
问题描述
我正在学习 RxJs,我正在寻求确认或更正我的假设.
我正在尝试在我可以在我的服务类的不同位置使用 .next()
的服务中创建一个公共只读 observable.我想知道这是否是正确的方法:
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();
- 用户可以订阅
myObservable$
- 我可以使用
myObservable.next(...);
它运行良好,但我有足够的经验知道我可能只是一个不知情的白痴(RxJS 是巨大的).对于所述用例,这是正确的模式和正确的对象吗?
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?
推荐答案
您的做法是正确的.然而,仍然有一个更短的符号.由于 Subject 已经是一个 Observable(它继承了 Observable 类),你可以将类型检查留给 TypeScript:
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;
您的服务的任何使用者都可以订阅 myObservable$
但不能调用 myObservable$.next()
因为 TypeScript 不允许您这样做(Observable 类没有任何 next()
方法).
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).
这实际上是推荐的做法,而且 RxJS 内部从不使用 asObservable
.有关更详细的讨论,请参阅:
This is actually the recommended way of doing it and RxJS internally never uses asObservable
anyway. For more detailed discussion see:
https://github.com/ReactiveX/rxjs/issues/2391一个>
看到一个非常相似的问题:应该在班级?
See a very similar question: Should rxjs subjects be public in the class?
这篇关于Observable vs Subject 和 asObservable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!