javascript - 返回主题仅供订阅

标签 javascript typescript rxjs observable subject

我的问题是关于在不允许接收者对主题执行 .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$ 可以公开了,因为它只是一个普通的 Observable。 TypeScript 不允许您调用例如 ExampleService.observable$.next() 因为这个方法在 Observables 上不存在。

如果您只使用 JavaScript,则可以使用 exampleSubject.asObservable() 从 Subject 返回 Observable。

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

关于javascript - 返回主题仅供订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54372300/

相关文章:

routing - Angular - 路由参数

javascript - 相当于 redux 'getState' 来自 rxjs 中的可观察对象

typescript - 使用命名导入或 'add' 字符串导入 RxJS

javascript - Angular 4. XHR 请求中的错误停止了链式可观察量

javascript - 如何在 Leaflet.js 中更改 map 中心

typescript - 解构函数参数对象并 ...rest

javascript - 循环遍历表以生成 json

angular - 与简单的媒体查询相比,使用 Angular Material BreakpointObserver API 有什么好处?

javascript - 在 Vue.js 中处理 JSON 文件后无效的 JSON 字符

javascript - 如何将 @Gbuomprisco/ng2-tag-input 与 angular-cli 一起使用?