我在我的 angular5 网站中使用 SignalR 来呈现文档锁定。我将集线器连接存储在数据服务中,很快广告用户登录,我将启动连接。在我需要集线器连接的每个组件中,我都有一个 Observable,在连接建立后,它会监听集线器。一切正常。但是刷新页面后,它不会显示 SignalR 命令的结果。如果我在该页面上单击或鼠标悬停,那么它将显示 SignalR 的结果!
这是登录后运行的代码:
startConnection(): void {
//Create the hub connection for SignalR
this.dataService.connection = $.hubConnection(this.dataService.getServerConn());
this.dataService.authProxy = this.dataService.connection.createHubProxy('auth');
this.dataService.authProxy.on('handler', () => { });
this.dataService.authProxyCreated = false;
this.dataService.connection.qs = { "AuthenticationToken": sessionStorage.getItem('UMToken') };
if (this.dataService.connection.state != $.signalR.connectionState.connected)
this.dataService.connection.start().done(() => {
console.log('Connected to SignalR hub!');
}).catch((error: any) => {
console.log('Hub error -> ' + error);
});
}
这是侦听集线器的组件中的代码:
ngOnInit() {
//SignalR
if (this.storeDataService.connection.state === $.signalR.connectionState.connected)
this.registerSignalR();
this.storeDataService.connection.stateChanged((change) => {
if (change.newState === $.signalR.connectionState.connected)
this.registerSignalR();
});
}
ngOnDestroy() {
this.storeDataService.authProxy.off('lockAuth');
this.storeDataService.authProxy.off('unlockAuth');
}
registerSignalR() {
this.storeDataService.authProxy.on('lockAuth', (authNo: string, username: string) => {
var auth = this.queueList.data.find(p => p.AuthNo == authNo);
if (auth) {
auth.LockedOn = new Date();
auth.LockedByUserName = username;
}
});
this.storeDataService.authProxy.on('unlockAuth', (authNo: string) => {
var auth = this.queueList.data.find(p => p.AuthNo == authNo);
if (auth) {
auth.RmiLockedOn = null;
}
});
}
这也是编辑页面中调用锁定的代码:
if (this.dataService.connection.state === $.signalR.connectionState.connected) {
this.dataService.authProxy.invoke('lock', this.authNo, this.userService.userName, this.userService.userId);
}
this.dataService.connection.stateChanged((change) => {
if (change.newState === $.signalR.connectionState.connected) {
this.dataService.authProxy.invoke('lock', this.authNo, this.userService.userName, this.userService.userId);
}
});