0

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?

Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • Are you using that service in some other components/services as well? Is there are particular reason why you are using BehaviourSubject instead of Subject? – munleashed Jun 27 '22 at 15:32

1 Answers1

0

I don't see your whole code but I guess that your service is provided in the root, which means that it won't get destroyed once your component gets destroyed.

if my assumptions are correct you have 2 options -

  1. u can provide the service at the component level instead of the app root.
  2. you can maintain the behavior subject in your component.
gil
  • 2,388
  • 1
  • 21
  • 29