2017-10-10 45 views
2

我做了一個角度的應用程序,每兩秒更新一個儀表板的HTTP GET請求。但是我經常收到HTTP錯誤429(太多請求)。如何使用保持連接與angular2 http服務

我在Firefox的開發工具的要求是​​「保活」用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); 
     } 
    ); 
} 
+1

聽起來像是WebSockets的https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API – jbrown

+0

耶@jbrown的情況,而且我的後端是Laravel(PHP)。我認爲在PHP中實現websockets非常複雜。我不認爲我可以有一個長期的PHP過程。 – alvaropgl

+1

https://laravel.com/docs/5.5/broadcasting –

回答

0

這是我用一個簡單的到期實現。

它有什麼會議並將會話發送到後端(每30秒)。如果彈出一個成功消息,它將會在註銷計時器上增加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()); 
    } 
相關問題