簡體   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