我制作了一个 Angular 应用程序,它每两秒发出一次 http GET 请求以更新仪表板。但我经常收到 HTTP 错误 429(请求过多)。
我在 Firefox 开发者工具中看到请求是“Keep Alive”,时间为 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);
}
);
}
最佳答案
这是我使用的一个简单的过期实现。
什么是它有一个 session 并将 session 发送到后端(每 30 秒)。如果弹出一条成功消息,它将向 logoutTimer 添加 15 分钟。如果日期高于 logoutTimer,那么它将自动注销。
localStorage 用于,如果您在主页上再次打开它,您的 session 可以用 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());
}
关于angular - 如何使用与angular2 http服务的保持连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46667972/