无法退订SignalR事件

时间:2019-01-22 15:55:24

标签: asp.net angular signalr broadcast subscription

我有多个Angular组件正在订阅SignalR集线器连接。我已经将SignalR集线器连接对象包装到角度服务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包装器,并在构造函数中调用了{{1 }} 方法。要取消订阅该事件,我在析构函数中调用.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()是否应该关闭当前的订阅?

0 个答案:

没有答案