Issue
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?
Solution
It is about encapsulation. In larger applications, it is a good idea to have only one place that emits to the shared stream (subject), which is in the service.
Then no other component can, for example, accidentally call complete()
on the subject. In the service, just provide one method in order to emit (emitNewValue in your example). A getter for the subject is not needed as exposing the subject with asObservable
provides components with a read-Only copy of the subject, which they can listen/subscribe to.
Answered By - Rasha Elsayed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.