如果连接失败,如何继续尝试从Angular服务订阅signalR?

编程入门 行业动态 更新时间:2024-10-23 21:27:28
本文介绍了如果连接失败,如何继续尝试从Angular服务订阅signalR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何继续尝试以安全的方式尝试连接到signalR,从而允许两次尝试之间至少间隔几百毫秒,直到建立连接为止;如果可以的话,有人可以提供一种更好的方法来处理各个阶段到网络套接字的连通性?

How can I keep attempting to connect to signalR in a safe way that allows a few hundred milliseconds (at least) in between attempts until the connection is established and if so, could someone provide a better way pf dealing with the various stages of connectivity to the web-sockets?

我们在.NET后端上使用signalR,我试图用它在Angular 4 UI中显示实时推送通知.连接时效果很好,但有时会出现2-3次连接的问题.如果将其放入catch块中以尝试重新连接,也会收到错误this.startSignalRListener is not a function.

We are using signalR on a .NET backend and I am trying to use it to display real-time push notifications in an Angular 4 UI. It works great when it connects, but there is a problem where sometimes it takes 2-3 times to connect. I also get an error this.startSignalRListener is not a function if I put it inside the catch block to try to reconnect that way.

任何建议将不胜感激.

我在package.json中使用"@aspnet/signalr-client": "^1.0.0-alpha2-final"

I am using "@aspnet/signalr-client": "^1.0.0-alpha2-final" in package.json

这是服务类中的一些代码...

Here is some of my code from my service class...

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' ]) .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`; this.hubConnection = new HubConnection(connection); this.hubConnection .start() .then(() => { this.onConnection(); }) .catch(err => { console.log('Error while establishing connection...'); }); } }

当连接失败时,如何最好地重新连接?任何建议都会对我有帮助,因为它在第一次尝试时经常会失败.

How can I best reconnect when a connection fails? Any suggestion would really help me out as it fails often on the first try.

推荐答案

您可以尝试使用 setTimeout 函数可延迟重新连接:

You can try to use the setTimeout function to delay your reconnects:

.catch(err => { console.log('Error while establishing connection... Retrying...'); setTimeout(() => this.startSignalRListener(), 3000); });

在这种情况下,建议您将this.hubConnection.on('domain_bid'从startSignalRListener中移出,以便仅将这些东西绑定一次.

In this case I suggest you to move the this.hubConnection.on('domain_bid' out of startSignalRListener to bind this stuff only once.

更多推荐

如果连接失败,如何继续尝试从Angular服务订阅signalR?

本文发布于:2023-11-02 14:56:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angular   signalR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!