问题描述
我想知道 BehaviorSubject
中以下代码中的两种方法是什么.
I am wondering what is the two approach in the following code in BehaviorSubject
.
据我所知:
asObservable 方法不仅将其转换为 Observable,还移除了 Observer 实现.因此你不能调用 next, error &在 asObservable() 返回的实例上完成.
但以下内容也让我感到困惑:
but the following also makes me confused:
通过仅公开 asObservable,您可以使用发出的值,但防止从创建此 BehaviorSubject 的服务外部更改 BehaviorSubject.为此,请使用 asObservable().
这些定义有什么问题吗?
Is there anything wrong with these definitions?
export class DataService {
// usage I : using getter
private messageSubject = new BehaviorSubject<any>(undefined);
getMessage(): BehaviorSubject<any> {
return this.messageSubject;
}
setMessage(param: any): void {
this.messageSubject.next(param);
}
// usage II : using asObservable()
private messageSubject = new BehaviorSubject<any>(undefined);
currentMessage = this.messageSubject.asObservable();
setMessage(param: any) {
this.messageSubject.next(param)
}
}
以上哪种方法更好用,或者这两种方法的优缺点是什么?
Which approach above is better to use or what is the pros and cons for these 2 approaches?
更新:上次我最终确定了正确的用法如下:
Update: Last time I finalised the correct usage as the following:
// usage III : using @martin's approach:
private messageSubject = new BehaviorSubject<any>(undefined);
public messages$: Observable<any> = this.messageSubject;
//should I set the observable still using the following method without any changing? Or do I need an update?
setMessage(param: any) {
this.messageSubject.next(param)
}
推荐答案
实际上,在 TypeScript 中推荐的方法只是通过这样的类型转换:
Actually, the recommended way of doing this in TypeScript is only by type casting like this:
private messageSubject = new BehaviorSubject<any>(undefined);
public messages$: Observable<any> = this.messageSubject;
这样,TypeScript 编译器就不会让您调用 next()
、error()
或 complete()
.仅在纯 JavaScript 中使用 RxJS 时才推荐使用 asObservable()
.例如,在 RxJS 源代码内部,它从不使用 asObservable()
即使它使用并暴露 Subjects =>大量观察.
This way it's TypeScript compiler who won't let you call next()
, error()
or complete()
. Using asObservable()
is recommened only when using RxJS in pure JavaScript. For example, internally in RxJS source code it never uses asObservable()
even though it uses and exposes Subjects => Observables a lot.
更多信息见讨论:https://github.com/ReactiveX/rxjs/pull/2408
这篇关于我应该在 BehaviorSubject 中使用 asObservable 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!