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

标签 javascript node.js angular typescript signalr

我怎样才能以安全的方式继续尝试连接到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/

相关文章:

javascript - 在两个页面之间重新加载数据

node.js - 使用 Node/express 和 Passport.js 无法登录并且没有错误消息

javascript - Angular 2 : Reply HttpHeaders from HttpResponse are stripped. 如何修复?

typescript - Angular 2 - 在下拉列表中设置选定值

javascript - 使用 JavaScript 在 HTML 中搜索 XML

javascript - Lookahead (?=模式) 没有前面的模式

javascript - 将 js 代码从 Jade 转换为 EJS

javascript - 如何通过使用属性(n)的密码请求获取 Node ID?

Angular 4嵌套http调用和合并数据

javascript - 如何在 coffeescript 中执行 "if undefined"?