When is asObservable()
needed on a Subject (e.g. BehaviorSubject) to get a observable of the subject? The subject isself can be casted to an Observable as well.
name1$
and name2$
?name1$
or name2$
)?import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs';
export class Person {
private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');
public get name1$(): Observable<string> {
return this.nameSubject.asObservable();
}
public get name2$(): Observable<string> {
return this.nameSubject;
}
public setName(value: string): void {
this.nameSubject.next(value);
}
}
Thank You for your answers in advance!
In general, it's recommended to use asObservable()
only when using RxJS in JavaScript. With TypeScript you can use just type casting and it won't let you call next()
and so on.
private nameSubject: BehaviorSubject<string> = new BehaviorSubject<string>('lorem');
public nameSubject$: Observable<string> = this.nameSubject;
This is the officially recommended way of turning Subjects to Observables in TypeScript.
For details see https://github.com/ReactiveX/rxjs/pull/2408#issuecomment-282077506.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With