When I find myself needing to use a variable in multiple components that can change over time, I typically store that variable in a service and encapsulate the value in a Subject. This allows every component to receive updates when next is called on the Subject.
However, I have come across tutorials cautioning against using Subjects in this manner. Instead, they suggest the following approach:
// in some service
private subject$: Subject<any> = new Subject();
subjectAsObservable: Observable<any> = this.subject$.asObservable();
But I have concerns about not being able to emit new values by calling next
when using an Observable in components.
My question is, what risks are associated with using a Subject in the following way:
// in some service
subject$: Subject<any> = new Subject();
And then subscribing to that subject in the components, where changes made to the variable trigger a call to next
, updating all subscribing components. Does this implementation pose any security issues?
Is the following implementation considered more secure compared to the previous one:
private subject$: Subject<any> = new Subject();
emitNewValue(value: any): void {
this.subject$.next(value);
}
getSubject(): Subject<any> {
return this.subject$:
}
I am unsure about the security risks involved. How should I properly handle the use of Subjects?