Angular 7 Communication through service subscribe

2020-05-08 06:45发布

问题:

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

回答1:

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.