我的问题是关于在不允许接收者对主题执行 .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/