繁体   English   中英

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

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

我正在使用 angular,试图与非父子组件通信。 所以我通过服务来传达它

服务.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();
}

主页.ts

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

所以当我在 Home 组件中点击提交时切换订阅被点击两次

如我所见,您的服务中有 3 个名称完全相同的字段。 其中2个被遗漏了。 你可以

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

在您的服务和组件中:

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

请注意,我删除了 @Output() 装饰器。 它仅在组件内部用于父子通信。

暂无
暂无

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

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