[英]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.