无法取消订阅 SignalR 事件

bil*_*ial 6 asp.net broadcast subscription signalr angular

我有多个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));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个组件,我想从中订阅通过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);
                });
    }
}
Run Code Online (Sandbox Code Playgroud)

当我最初访问此组件描述的页面时,一切都按预期工作(console.log()正在记录我收到的每条消息)。

当我离开页面时,MyHubConnection.off('Broadcast');被调用。然后我再次访问上一页后,调用了构造函数并进行了另一个订阅,但是前一个没有关闭,我收到了两次console.log()调用。

我犯的错误在哪里?MyHubConnection.off('Broadcast');离开页面时不应该关闭当前订阅吗?