我怎样才能以安全的方式继续尝试连接到signalR,在尝试之间允许几百毫秒(至少)直到建立连接,如果是这样,有人可以提供更好的方法来处理各个阶段与网络套接字的连接?
我们在 .NET 后端上使用 signalR,我尝试使用它在 Angular 4 UI 中显示实时推送通知。连接时效果很好,但有一个问题,有时需要2-3次才能连接。如果我将其放入 catch block 中以尝试以这种方式重新连接,我还会收到错误 this.startSignalRListener is not a function
。
如有任何建议,我们将不胜感激。
我在 package.json 中使用 "@aspnet/signalr-client": "^1.0.0-alpha2-final"
这是我的服务类中的一些代码...
import { HubConnection } from '@aspnet/signalr-client';
@Injectable()
export class RealTimeService implements OnInit {
private hubConnection: HubConnection;
constructor() {}
ngOnInit() {
this.startSignalRListener();
}
public onConnection(): void {
const domain = this.state.domain;
this.hubConnection
.invoke('WatchSomething', [ 'abc.com' ])
.catch(err => console.error('signalR error: ', err));
this.hubConnection.on('some_thing', (res: any) => {
console.log('do stuff...', res);
});
}
public startSignalRListener() {
const connection = `www.realtimeapi.com`;
this.hubConnection = new HubConnection(connection);
this.hubConnection
.start()
.then(() => {
this.onConnection();
})
.catch(err => {
console.log('Error while establishing connection...');
});
}
}
连接失败时如何最好地重新连接?任何建议都会真正帮助我,因为它经常在第一次尝试时失败。
最佳答案
您可以尝试使用setTimeout延迟重新连接的函数:
.catch(err => {
console.log('Error while establishing connection... Retrying...');
setTimeout(() => this.startSignalRListener(), 3000);
});
在这种情况下,我建议您将 this.hubConnection.on('domain_bid'
) 移出 startSignalRListener
,以便仅绑定(bind)此内容一次。
关于javascript - 如果连接失败,我如何继续尝试从 Angular 服务订阅 signalR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49591843/