通过两次调用服务订阅方法进行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
service.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
ngOnInit() {
this.service.change.subscribe(_toggle=> {
//some code here
}
}
因此,当我单击主页"组件中的提交"时,切换订阅会被击中两次
so when I click on submit in Home component toggle subscribe get hit twice
推荐答案
如我所见,您的服务中有3个字段具有完全相同的名称.他们中的两个被错过了.你可以做
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屋!
查看全文