[英]Why are my messages from BehivourSubject duplicated every new recieved message?
我正在使用 BehivourSubject 接收數據,也使用 websocket 但 websocket 現在並不重要。 現在非常重要,為什么我總是從 BehivourSubject 收到重復的消息。
檢查服務中的代碼:
hubMessage$ = new BehaviorSubject({});
public startConnection = (id: number) => {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://api/hub')
.build();
this.hubConnection
.start()
.then(() => {
console.log('connection established')
}
)
.catch(err => {
console.log('Error while starting connection: ' + err)
this.retryConnection();
})
}
public newLocationRecieved() {
this.hubConnection.on('NewLoc', (data) => {
console.log('new location recieved' , data)
this.hubMessage$.next(data);
})
}
public sendDriverId(id: number = 1) {
this.hubConnection.send('SubOnDriver', { driverId: id })
}
每 20 秒我就有一個新的位置。 我需要從這個 hubMessage 中刪除以前的數據,或者什么,但我的軟件在一分鍾后崩潰,因為重復的消息。
想象一下您的消息是重復的。 先得到一個,然后是兩個,然后是四個,然后是六十個..32....64..
為什么?
如何解決這個問題?
我在組件中使用此消息:
組件代碼:
ngOnChanges() {
this.dispatchDetails;
this.createMarkers();
}
createMarkers() {
console.log('Connection start right now ', this.dispatchDetails)
this.newCoordinate();
}
private newCoordinate = () => {
this.signalRService.hubMessage$.subscribe(
(data: any) => {
console.log('recieved new coordinate ?', data); // HERE I GOT SO MUCH DUPLICATED MESSAGE
this.signalRService.newLocationRecieved()
this.locationCoords = data;
if (this.locationCoords.location) {
this.latitude = this.locationCoords?.location?.latitude
this.longitude = this.locationCoords?.location?.longitude
}
}
)
}
我可能需要清除我的變量...或者 websocket 連接有問題?
websocket 連接是否重復? 我不相信
您可能知道我無法制作最少的復制代碼,因為這些代碼是 web sockets...
這是因為您從ngOnChanges
生命周期調用createMarkers()
function。 當組件范圍值發生變化時, ngOnChanges
將被一次又一次地調用。 因此,將一次又一次地創建新訂閱,因此您有一堆重復的消息。 只有當您創建一個組件或任何一次時,您才需要調用該 function 。 或者您需要先終止現有訂閱,然后再創建新訂閱。
您已訂閱this.signalRService.hubMessage$
並且在您從該行為主題收到的任何新數據上,您調用this.signalRService.newLocationRecieved()
this.signalRService.hubMessage$.subscribe(
(data: any) => {
...
this.signalRService.newLocationRecieved()
}
這反過來又創建了一個全新的回調
public newLocationRecieved() {
this.hubConnection.on('NewLoc', (data) => {
this.hubMessage$.next(data);
})
}
因此你的重復值。 我建議將回調移動到startConnection
function
public startConnection = (id: number) => {
...
this.hubConnection.on('NewLoc', (data) => {
console.log('new location recieved', data)
this.hubMessage$.next(data);
});
}
編輯:
還有this.createMarkers();
應該將 ngOnChanges ngOnInit
ngOnChanges
全部歸功於@Liu Zhang
在newCoordinate
內的消息處理程序中,您調用this.signalRService.newLocationRecieved()
,它會設置另一個事件處理程序,將另一條消息發布到同一個hubMessage$
中。 您只想執行一次,可能在startConnection
中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.