On an Angular 10 application I need to send a message between components so I created the service:
export class MemoService {
private subject = new Subject<Memo>();
send(code: MemoCode, data?: any) {
this.subject.next(new Memo(code, data));
}
clear() {
this.subject.next();
}
get(): Observable<Memo> {
return this.subject.asObservable();
}
}
On a component consuming this service I have:
private memo: Subscription;
private user: BehaviorSubject<User> = new BehaviorSubject<User>(null);
constructor(private memoService: MemoService) {
this.getUser().subscribe((result: GetUserResponse) => this.user.next(result));
this.memo = this.memoService.get().subscribe((memo: Memo) => {
if (memo.code == MemoCode.AuthenticatedUserModified)
this.getUser().subscribe((result: GetUserResponse) => this.user.next(result));
});
}
The idea is when a specific User is updated I send a Memo
to other components using the MemoService
.
Question
Should I use Subject or BehaviorSubject in both Component and Service?