这个问题通常是由未正确处理SignalR连接和断开连接引起的。可以使用以下代码示例来展示如何在Angular中正确创建和销毁SignalR连接:
首先,在component.ts文件中引入SignalR客户端库:
import * as signalR from "@microsoft/signalr";
接下来,在component类中声明以下变量:
private hubConnection: signalR.HubConnection; private message: string = "";
然后,在ngOnInit方法中创建SignalR连接:
ngOnInit() { this.hubConnection = new signalR.HubConnectionBuilder() .withUrl('/hub') .build();
this.hubConnection.start() .then(() => console.log('Connection started')) .catch(err => console.log('Error while starting connection: ' + err)); }
在ngOnDestroy方法中销毁SignalR连接:
ngOnDestroy() { this.hubConnection.stop() .then(() => console.log('Connection stopped')) .catch(err => console.log('Error while stopping connection: ' + err)); }
使用上面的示例代码,可以确保SignalR连接在组件加载时建立,在组件卸载时正确关闭,从而解决Angular signalR socket返回每次更改路由时始终返回相同的值的问题。