Return 主题仅供订阅

Return subject only for subscription

我的问题是关于在不允许接收者对主题执行 .next() 的情况下返回对主题的引用。

例如,我有一个服务,其中包含一个主题并且可以触发关于该主题的新事件

class ExampleService {
  private exampleSubject = new Subject<boolean>;

  // Ideally the only way to call next on the subject
  doNext() {
    this.exampleSubject.next(true);
  }

  getSubject() {
    // Ideally returning a reference to the subject but only with the 
    // ability to subscribe and listen for events, not to call .next()
    return this.exampleSubject;
  }
}

同样,我正在寻找一种让其他组件调用此服务并获取主题但只能订阅和侦听更改的方法,他们不应该能够进行更改。

ExampleService.getSubject().subscribe(() => {
  //do something 
}) // ok
ExampleService.getSubject().next(true) // error/not allowed

官方推荐的执行此操作的方法(假设您使用的是 TypeScript)是强制将 Subject 重新键入一个 Observable(Subject 与其他对象一样是 Observable):

class ExampleService {
  private exampleSubject = new Subject<boolean>();
  observable$: Observable<boolean> = this.exampleSubject;

  ...
}

现在 observable$ 可以是 public 因为它只是一个普通的 Observable。 TypeScript 不允许您调用例如 ExampleService.observable$.next() 因为这个方法在 Observables 上不存在。

如果您只使用 JavaScript,您可以使用 exampleSubject.asObservable() 到 return 从主题观察。

关于 RxJS 的 GitHub 的讨论也很相关:https://github.com/ReactiveX/rxjs/pull/2408