Asp.net Can';t取消订阅信号器事件
我有多个Asp.net Can';t取消订阅信号器事件,asp.net,angular,signalr,broadcast,subscription,Asp.net,Angular,Signalr,Broadcast,Subscription,我有多个Angular组件订阅信号器集线器连接。我已将信号器集线器连接对象包装到角度服务,hubconnection.service.ts: import { Injectable } from '@angular/core'; import { HubConnectionBuilder, HubConnection } from '@aspnet/signalr'; @Injectable() export class HubConnectionService { public My
Angular
组件订阅信号器
集线器连接。我已将信号器
集线器连接对象包装到角度服务,hubconnection.service.ts
:
import { Injectable } from '@angular/core';
import { HubConnectionBuilder, HubConnection } from '@aspnet/signalr';
@Injectable()
export class HubConnectionService {
public MyHubConnection: HubConnection;
constructor() {
this.MyHubConnection = new HubConnectionBuilder()
.withUrl('/sensorHub')
.build();
this.MyHubConnection
.start()
.then(() => console.log('[HubConnectionService] Connection started'))
.catch(err => console.log('[HubConnectionService] Error while starting connection: ' + err));
}
}
现在我有了一个组件,我想从中订阅通过SignalR
集线器接收的数据,为此我导入了SignalR
包装器,并在构造函数中调用.on()
方法。要取消订阅该事件,我调用析构函数中的.off()
方法:
export class RawdataComponent implements OnInit {
constructor(private hubConnectionService: HubConnectionService) { }
ngOnDestroy() {
this.hubConnectionService.MyHubConnection.off('Broadcast');
}
ngOnInit() {
this.hubConnectionService.MyHubConnection.on('Broadcast',
function(sender, message) {
console.log('New message received: ' + message);
});
}
}
当我最初访问此组件描述的页面时,一切都按预期工作(console.log()
正在记录我收到的每条消息)
当我离开页面时,MyHubConnection.off('Broadcast')代码>被调用。然后,在我再次访问上一页后,调用构造函数并进行另一个订阅,但上一个未关闭,我得到两个console.log()
调用
我犯的错误在哪里?不应该MyHubConnection.off('Broadcast')代码>在我离开页面时关闭当前订阅