简体   繁体   English

通过两次调用服务订阅方法进行 Angular 7 通信

[英]Angular 7 Communication through service subscribe method called twice

I'm using angular, trying to communicate to a component that is not parent-child.我正在使用 angular,试图与非父子组件通信。 So I'm communicating it through service所以我通过服务来传达它

service.ts服务.ts

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

search.ts search.ts

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

Home.ts主页.ts

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

so when I click on submit in Home component toggle subscribe get hit twice所以当我在 Home 组件中点击提交时切换订阅被点击两次

as I see you have 3 fields with exact the same name in your service.如我所见,您的服务中有 3 个名称完全相同的字段。 2 of them are missed.其中2个被遗漏了。 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.请注意,我删除了 @Output() 装饰器。 it is used only inside components just for parent-child communication.它仅在组件内部用于父子通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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