如果连接未处于“已连接”状态,则无法发送数据

haf*_*mid 8 signalr signalr-hub typescript angular angular6

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

信号R.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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

我是 SignalR 和 Angular 的新手,为什么我一直收到这个错误?

use*_*167 0

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

<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Run Code Online (Sandbox Code Playgroud)

如果您不导航到*.cshtml包含上述内容的页面,则 SignalR 将无法为您创建 Hub。如果您希望它在整个网络应用程序中可用,请将以上内容放入_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.
Run Code Online (Sandbox Code Playgroud)

更多详情请参阅:

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

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

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