【问题标题】:Cannot send data if the connection is not in the 'Connected' State如果连接未处于“已连接”状态,则无法发送数据
【发布时间】:2019-05-21 13:49:13
【问题描述】:

在 Angular 6 中使用 SignalR 进行一个非常简单的调用来设置连接/停止,其中我有以下代码:

signalR.helper.ts

  public static setupHub<T>(hubUrl: string, eventName: string, callback: (data: T) => void, ...params: SignalRParam[]): HubConnection {
    const token = localStorage.getItem(appConstant.token);
    const url = this.buidlUrl(hubUrl, ...params);
    const connection = new HubConnectionBuilder()
        .withUrl(url,
            { transport: HttpTransportType.WebSockets, accessTokenFactory: () => token })
        .build();
    environment.production && connection.start();
    !environment.production && connection.start().catch(err => console.error(err.toString()));
    connection.on(eventName, callback);
    return connection;
}

如果我尝试在我的页面上登录,我会在控制台上不断收到此错误:

signalR.helper.ts:19 错误:如果连接未处于“已连接”状态,则无法发送数据。

我是 SignalR 和 Angular 的新手,为什么我不断收到此错误?

【问题讨论】:

    标签: angular typescript signalr angular6 signalr-hub


    【解决方案1】:

    请提供更多详细信息,例如您的Startup.cs,或您在*.cshtml 中添加以下行的位置:

    <script src="~/lib/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/chat.js"></script>
    

    如果您不导航到具有上述内容的 *.cshtml 页面,则 SignalR 将无法为您创建集线器。如果您希望它在整个网络应用程序中可用,请将以上内容放在_Layout.cshtml

    这将导致如下错误:

    POST http://myserver.com/chatHub/negotiate 404 (Not Found)
    (anonymous) @ XhrHttpClient.ts:84
    XhrHttpClient.send @ XhrHttpClient.ts:30
    Utils.ts:179 [2019-06-14T19:21:39.774Z] Error: Failed to complete negotiation with the server: Error: Not Found
    ConsoleLogger.log @ Utils.ts:179
    Utils.ts:179 [2019-06-14T19:21:39.774Z] Error: Failed to start the connection: Error: Not Found
    Error: Cannot send data if the connection is not in the 'Connected' State.
    

    更多详情请看:

    概述: https://docs.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-2.2

    集线器: https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2

    客户: https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.1#call-hub-methods-from-client

    【讨论】:

      【解决方案2】:

      在调用任何方法之前,确保从“.start()”返回的承诺已经解决。您可能想要更改您的方法以返回承诺,以便您可以将其他方法链接起来。或者在方法中切换到使用 async/await 模式。

      另外,请确保您没有意外调用“.stop()”。在我的例子中,我有一个观察用户是否通过身份验证并在他们注销时调用“.stop()”。问题是 observable 表明在页面加载时用户在短时间内没有经过身份验证 - 这导致了一种竞争条件,有时它可以工作,有时它不会。

      【讨论】:

        猜你喜欢
        • 2021-10-09
        • 2020-01-21
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2020-11-06
        • 2019-06-26
        • 1970-01-01
        相关资源
        最近更新 更多