I'm getting the data multiple times , when I'm subscribing behavior subject from service in angular 14

359 Views Asked by At

I have a behavior subject in main component when the user click on update button it will emit true/false based on the condition.

That behavior subject is subscribed in another component and based on that true/false I need to show or hide rows.

Problem is behavior subject variable is emitted only one time in main but subscribed multiple times in other component.

my code : in service.ts

      public sendToRenderer = new BehaviorSubject<boolean>(true);
      public recievedData=this.sendToRenderer.asObservable();
      changeData(data: boolean) {
      this.sendToRenderer.next(data)
      }

tried with subject also like below:(but same response)

      public sendToRenderer = new Subject<boolean>();
      public recievedData=this.sendToRenderer.asObservable();
      changeData(data: boolean) {
      this.sendToRenderer.next(data)
      }
   

in main component.ts

       onUpdate(e: any) {
           this.uploadService.changeData(this.isRemarksUpdated)
            //this.isRemarksupdated is comning as true/false from other method
         }

in other component.ts

    ngOnInit(): void {
      this.subscripition= this.uploadService.recievedData.subscribe((data)=>{
      this.ispreFundEdited=data
      })
    }

when I'm using this.ispreFundEdited in any other method coming as undefined for the first time then coming true/false

here data getting multiple times like below (false/true)

6 false

what I have tried :

I have tried with using pipe like ".pipe(take(1)).subscribe(()=>{})", but no luck.

1

There are 1 best solutions below

0
Urtgard On

this.ispreFundEdited can be undefined if you use it before the assignment in subscribe((data) => ...) happens.

Possible reasons why you see the data multiple times:

  1. You call onUpdate multiple times.
  2. You don't unsubscribe from your subscription.
  3. You reuse your other component multiple times. Use shareReplay or share in your service depending on your use case: public recievedData$ = this.sendToRenderer.asObservable().pipe(shareReplay(1));