繁体   English   中英

如何使用angular2 http服务保持活动连接

[英]how to use keep alive connection with angular2 http service

我做了一个角度应用程序,每隔两秒发出一次http GET请求来更新仪表板。 但我经常收到HTTP错误429(请求太多)。

我在Firefox开发人员工具中看到请求是“Keep Alive”,时间为5秒,所以我认为每次调用都是打开与服务器的连接而不是重用它

如何判断角度重用连接? 或者如何避免429? 只有3或4个并发客户端。

相关代码如下:

ngOnInit() {
    this.interval = Observable.interval(environment.dashboard_refresh_rate).subscribe(x => {
        this.getLockersFromService();
    });
    this.getLockersFromService();
}

ngOnDestroy() {
    this.interval.unsubscribe();
}

getLockersFromService() {
    this.http.get('/dashboard').subscribe(
        data => {
            this.showDashboard(data);
        },
        (err: HttpErrorResponse) => {
            this.showErrorResponse(err);
        }
    );
}

这是我使用的一个简单的过期实现。

什么是会话并将会话发送到后端(每30秒)。 如果弹出一个成功消息,它将向logoutTimer添加15分钟。 如果日期高于logoutTimer,那么它将自动注销。

localStorage用于,如果在主页面上再次打开它,则可以使用timeFithTeen重新激活会话。

 constructor(private router: Router, private soap: SoapRequest) {  //soap is your rest 
        if (localStorage.getItem('logoutTimer') === null) {
            this.timeFithTeen();
        }   
    }



 ngOnInit() {
        Observable.timer(2000, 30000).subscribe(t => {
            let date = new Date();
            this.soap.keepAlive().then((response: any) => {
                localStorage.removeItem('logoutTimer');
                this.timeFithTeen();
            }), ((error: any) => {
                console.log(error);
            });
            if (date >= new Date(localStorage.getItem('logoutTimer'))) {
                localStorage.removeItem('sessionExpired');
                localStorage.setItem('sessionExpired', 'Session expired');
                this.router.navigateByUrl('/login');
            }
        });
    }
        private timeFithTeen() {
        let logoutTimer = new Date();
        logoutTimer.setMinutes(logoutTimer.getMinutes() + 15);
        localStorage.setItem('logoutTimer', logoutTimer.toString());
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM