SignalR 集线器连接 StateChanged 客户端不工作

SignalR hub connection StateChanged not working client

使用 .net Core 并使用本教程设置所有内容:https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio

我希望能够根据本教程使用生命周期事件:https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

然而我得到:

connection.stateChanged or connection.disconnected is not a function

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.start().then(function () {
}).catch(function (err) {
    return console.error(err.toString());
});

connection.stateChanged(function () {
    console.log('in');
});

我想在客户端检测到“断开连接”。

HubConnectionState 上的 MS Doc,只有 2 个状态:

  • 断开连接
  • 已连接

这些状态通过连接中的状态 属性 公开,但没有任何其他状态。

根据护士在 this github issue 中所说的,start Promise 让您知道连接何时开始,而 closed 事件让您知道它已停止。它们没有自动重新连接,因此只有这些是状态转换。

所以你可以像上面Dennis1679说的那样使用下面的方法

connection.onclose(function(){
    console.log('connecition closed');
});