connection.closed不是函数SignalR

时间:2018-07-23 20:11:50

标签: asp.net-core signalr signalr.client asp.net-core-signalr

我对SignalR中的关闭事件感到困惑。显然,有人称它为什么。 onClosed()closed()

在客户端的SignalR侦听器中,我正在尝试实现此事件,但始终收到错误消息,指出它不是函数。我尝试了onClosed()closed()。同样的错误。如何在客户端检测关闭事件?

const signalRListener = () => {

   connection.on('new_message', message => {

      // Handle incoming message.
      // This is working fine.
   })

   connection.closed(e => {

       // Try to restart connection but I never get here to due error I'm receiving
   })

}

我在做什么错了?

这是我开始建立连接的方式:

export const signalRStart = (token) => {

    connection = new signalR.HubConnectionBuilder()
        .withUrl("/chat?access_token=" + token)
        .configureLogging(signalR.LogLevel.Information)
        .build();

    // Set connection time out
    connection.serverTimeoutInMilliseconds = 30000;

    // Start connection
    connection.start();

    // Invoke listener
    signalRListener();
}

1 个答案:

答案 0 :(得分:4)

  

最佳做法是,在connection.start之后调用connection.on,以便在接收到任何消息之前先注册您的处理程序。

export const signalRStart = (token) => {

    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chat?access_token=" + token)
        .configureLogging(signalR.LogLevel.Information)
        .build();

    // Set connection time out
    connection.serverTimeoutInMilliseconds = 30000;

    //register listeners

    //Registers a handler that will be invoked when the hub method with the specified method name is invoked.
    connection.on('new_message', message => {    
        // Handle incoming message.
        // This is working fine.
    });

    //Registers a handler that will be invoked when the connection is closed.
    connection.onclose(e => {
        // ...
    });

    // Start connection
    connection.start();

};

引用ASP.NET Core SignalR JavaScript client

引用SignalR JavaScript API - HubConnection class