简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM