2017-10-10 138 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()); 
    }