Everytime I have to use a variable in different components which can be changed over time, I store that variable in a service and wrap the value in a Subject such that every component register changes when next is called. But then I see tutorials where it is mentioned that one has to be careful when using subjects. They do the following:
// in some service
private subject$: Subject<any> = new Subject();
subjectAsObservable: Observable<any> = this.subject$.asObservable();
and then the observable is used in the components but then I would not be able to call next
to emit new values.
Is there any risk when using subject the following way:
// in some service
subject$: Subject<any> = new Subject();
and then subscribe to that subject in the components and if components make changes to the variable, next
is called and every component that subscribes to that subject gets the new value.
Is the following implementation different (more "secure") to the implementation above:
private subject$: Subject<any> = new Subject();
emitNewValue(value: any): void {
this.subject$.next(value);
}
getSubject(): Subject<any> {
return this.subject$:
}
I do not quite get the security risks. How would I deal correctly with subjects?
CodePudding user response:
It is about encapsulation. In larger applications, it is good idea to have onlyone place that emits to the shared stream (subject), which is the service. Then no other component can for example accidently call complete() on the subject. In the service just provide one method to emit (emitNewValue in your example). No getter for the subject is needed as exposing the subject with asObservable provides components with a read-Only copy of the subject, which they listen/subscribe to.