Search code examples
angulartypescriptrxjsangular-services

Rxjs Subscription triggers more than once


It's very mysterious my subscription is getting triggered more than once - I don't know what was my mistake - I followed the same method on another but it doesn't get triggered more than once

 @Injectable({
  providedIn: 'root'
})
export class CommonService {

  constructor() {
    this.getpatientId = this.bindPatientId.asObservable();
  }

  bindPatientId: Subject<number> = new Subject<number>();
  getpatientId: Observable<number>;

  setPatientId(patientId: number) {
    this.bindPatientId.next(patientId);
  }

  bindTabId: Subject<number> = new Subject<number>();
}

Setting new value to the Subject

 toggleProfile(patientId: number) {
    this.commonService.setPatientId(patientId);
    this.route.navigate(['/endrolPatient']);
  }

Listening from another component

ngOnInit() {
    this._common.getpatientId.subscribe(
      (res) => {
        this.patientID = res;
        console.log("console inside observable", this.patientID);
      });
}

In my console when I pass 123 - I'm getting console inside observable 123 but after the first observer rest all the subscriptions get doubled and logging twice in my console - Please help me to fix it


Solution

  • That is probably because your component is getting destroyed and created again. So when your component destroys, you have to destroy all the subscriptions. You can do this in ngOnDestroy life cycle method

    code:

    class MyComponent implements OnInit, OnDestroy {
    
    private sub: Subscription;
    
    ngOnInit() {
        this.sub = this._common.getpatientId.subscribe(
          (res) => {
            this.patientID = res;
            console.log("console inside observable", this.patientID);
          });
    }
    
    ngOnDestroy(){
       this.sub.unsubscribe():
    }