简体   繁体   English

Observable vs Subject和asObservable

[英]Observable vs Subject and asObservable

I am learning RxJs, I am seeking confirmation or correction on my assumption. 我正在学习RxJs,我正在寻求对我的假设进行确认或更正。

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. 我试图在服务中创建一个public read only observable,我可以在我的服务类的不同位置使用.next() 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$ 用户可以订阅myObservable$
  • I can use myObservable.next(...); 我可以使用myObservable.next(...);

It works perfectly but I am experience enough to know that I may just be being an unwitting idiot (RxJS is huge). 它的工作完美,但我有足够的经验知道我可能只是一个不知情的白痴(RxJS很大)。 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: 由于Subject已经是一个Observable(它继承了Observable类),你可以将类型检查留给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). 您的服务的任何消费者都可以订阅myObservable$但是无法调用myObservable$.next()因为TypeScript不允许您这样做(Observable类没有任何next()方法)。

This is actually the recommended way of doing it and RxJS internally never uses asObservable anyway. 这实际上是推荐的做法,RxJS内部从不使用asObservable For more detailed discussion see: 有关详细讨论,请参阅:

See a very similar question: Should rxjs subjects be public in the class? 看到一个非常相似的问题: rxjs科目应该在课堂上公开吗?

In project we are using this kind of Observables, this is giving you proper encapsulation to your private observable, but you still can call next() using some public method. 在项目中我们使用这种Observables,这给你适当的封装到你的私有observable,但你仍然可以使用一些公共方法调用next()

      private sourceName = new Subject<T>();
      name = this.sourceProductName.asObservable();

      sendName(item: T) {
        this.sourceName.next(item);
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM