Search code examples
javascriptangulartypescriptrxjsangular7

Angular 7 Communication through service subscribe method called twice


I'm using angular, trying to communicate to a component that is not parent-child. So I'm communicating it through service

service.ts

Istoggle=false; 
@Output() change: EventEmitter < boolean > = new EventEmitter();
toggle() {
    this.Istoggle= !this.Istoggle;
    this.toggle.emit(this.Istoggle);
}

search.ts

submit():void{
  this.service.toggle();
}

Home.ts

ngOnInit() {    
   this.service.change.subscribe(_toggle=> {
           //some code here
    }
}

so when I click on submit in Home component toggle subscribe get hit twice


Solution

  • as I see you have 3 fields with exact the same name in your service. 2 of them are missed. you could do

    value=false; 
    search: EventEmitter < boolean > = new EventEmitter();
    toggle() {
       this.value = !this.value;
       this.search.emit(this.value);
    }
    

    in your service and in component:

    ngOnInit() {    
      this.service.search.subscribe(value => {
           //some code here
      }
    }
    

    note that I removed @Output() decorator. it is used only inside components just for parent-child communication.