【问题标题】:how to use keep alive connection with angular2 http service如何使用与 angular2 http 服务的保持连接
【发布时间】:2018-03-21 22:24:25
【问题描述】:

我制作了一个 Angular 应用程序,它每两秒发出一次 http GET 请求以更新仪表板。但我经常收到 HTTP 错误 429(请求过多)。

我在 Firefox 开发者工具中看到请求是“保持活动状态”,时间为 5 秒,所以我认为每个调用都是打开与服务器的连接而不是重用它

如何告诉 Angular 重用连接?或者如何避免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);
        }
    );
}

【问题讨论】:

标签: angular rest http webservice-client angular2-http


【解决方案1】:

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

它有一个会话并将会话发送到后端(每 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());
    }

【讨论】:

    猜你喜欢
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多