alvaropgl
alvaropgl

Reputation: 850

how to use keep alive connection with angular2 http service

I made an angular application that is making http GET request every two seconds to update a dashboard. But too often I receive a HTTP error 429 (Too Many Request).

I saw in the Firefox developer tools that the request is "Keep Alive" with a time of 5 seconds, so I think each call is opening a connection to the server and not reusing it

How can I tell angular to reuse the connection? or how can avoid a 429? Only have 3 or 4 concurrent clients.

The relevant code is below:

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);
        }
    );
}

Upvotes: 4

Views: 6535

Answers (1)

Swoox
Swoox

Reputation: 3740

This is a simple expire implementation I used.

What is does it has a session and send the session to the backend (every 30 sec). If a succes message pop up it will add 15mins to the logoutTimer. If the date is higher then logoutTimer then it will logout automatic.

localStorage is used for, if you open it again on the main page your session can be reactivated with 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());
    }

Upvotes: 0

Related Questions