2017-09-20 72 views
0

我有一個EventEmitter服務,如果數據更改,它將被觸發。角度:未收到事件發射器

@Output() reservationChangedEvent = new EventEmitter<any>(); 

public notifyReservationsChanged() { 
     this.reservationChangedEvent.emit({}); 
    } 

數據更改由從控制器啓動的模式觸發。

在我的控制器我認購這些事件:

ngOnInit() { 
     ... 
     this.reservationService.reservationChangedEvent.subscribe(() => this.reloadData()); 
    } 

我的問題是我不能接受我的概述組件事件。如果我在我的服務或我的模式中訂閱活動(用於檢查),我確實收到它們。

任何想法爲什麼總覽控制器無法接收事件?

+0

此[鏈接](https://rahulrsingh09.github.io/AngularConcepts/event)可能會幫助 –

回答

1

你應該改變:

@Output() reservationChangedEvent = new EventEmitter<any>(); 

到:

reservationChangedSubject = new Subject<any>(); 
reservationChangedEvent = this.reservationChangedSubject.asObservable() 

這:

public notifyReservationsChanged() { 
    this.reservationChangedEvent.emit({}); 
} 

到:

public notifyReservationsChanged() { 
    this.reservationChangedSubject.next({}); 
} 
+0

是你的當然?下一個屬性Observable類型上不存在 netshark1000

+1

您應該調用next()on Subject ofc。固定。 –

+0

做到了,但沒有任何變化。是this.reservationService.reservationChangedEvent.subscribe(()=> this.reloadData());仍然正確? – netshark1000

0

@Output()EventEmitter僅用於組件,不用於服務。

對於服務,您應該使用Subject來代替。

您的服務應該包含:

private reservationChangedSource = new Subject<any>(); 
reservationChanged$ = this.reservationChangedSource.asObservable(); 

notifyReservationsChanged() { 
    this.reservationChangedEvent.next({}); 
} 

在您的組件:

reservationChangeSubscription: Subscription; 

ngOnInit() { 
    ... 
    this.reservationChangeSubscription = this.reservationService.reservationChanged$ 
     .subscribe(() => this.reloadData()); 
} 

ngOnDestroy() { 
    this.reservationChangeSubscription.unsubscribe(); 
}