Angular 7 Communication through service subscribe method called twice

不问归期 提交于 2020-01-22 02:16:06

问题


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.



来源:https://stackoverflow.com/questions/54784980/angular-7-communication-through-service-subscribe-method-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!