I have a component with following ngOnInit and save method. I have a behaviorsubject which i am using tonotify when save action is performed. Default value is null. but after i save and reopen the component, it is coming up with previous value and again making service call which it shouldn't. What am i doing wrong here?
component:
ngOnInit(): void {
this.templateSaveService.templateSaveSubject
.pipe(
takeUntil(this.destroy$),
filter((auditTemplate) => auditTemplate !== null),
switchMap((auditTemplate) => {
return this.auditTemplateSaveService
.createTemplate(auditTemplate) //it is getting called for first time as well.
.pipe(
map((response) => ({
...auditTemplate,
id: response.body.id
})),
catchError((error) => this.handleError(error))
);
})
)
.subscribe((template) => {
this.isSavingData = false;
this.toasterService.success('Template has been saved successfully');
});
}
save(): void {
this.templateSaveService.saveAuditTemplate(this.auditTemplate);
}
service:
templateSaveSubject = new BehaviorSubject<AuditTemplate>(null);
saveAuditTemplate(auditTemplate: AuditTemplate): void {
this.templateSaveSubject.next(updatedTemplate);
clearSaveSubject(): void {
this.templateSaveSubject .next(null);
}
I can fix by set the subject to null in component ngDestroy()
ngOnDestroy(): void {
this.auditTemplateSaveService.clearSaveSubject();
this.destroy$.next(true);
this.destroy$.complete();
}
But would like to know why the behaviour subject value not cleared initially and is there any other better solution for this?