通过两次调用服务订阅方法进行 Angular 7 通信 [英] Angular 7 Communication through service subscribe method called twice
本文介绍了通过两次调用服务订阅方法进行 Angular 7 通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 angular,试图与非父子组件通信.所以我通过服务来传达它
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
}
}
所以当我在 Home 组件中点击提交时切换订阅被点击两次
so when I click on submit in Home component toggle subscribe get hit twice
推荐答案
如我所见,您的服务中有 3 个名称完全相同的字段.其中2个被遗漏了.你可以做
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);
}
在您的服务和组件中:
ngOnInit() {
this.service.search.subscribe(value => {
//some code here
}
}
请注意,我删除了 @Output() 装饰器.它仅用于组件内部,仅用于父子通信.
note that I removed @Output() decorator. it is used only inside components just for parent-child communication.
这篇关于通过两次调用服务订阅方法进行 Angular 7 通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文