3

I'm trying to make an angular 2 version of an old fashion application. There is a service that sends recurring request to a server to check if user is being logged in or not. The login guard will check the polling to see if the login session result( get from the request) is valid or not to return a right signal to the route.

This is the function is my service:

getUser(): Observable<User> { return this.http.get<User>(this.userUrl); }

This is the canActive function from my guard:

canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { // const isLoggedIn = this.authService.isLoggedIn(); return this.authService.getUser().flatMap((data) => { console.log(data); if (data.id === 1 && data.name === 'Beany' ) { console.log(1111) return Observable.of(true); } else { console.log(2222) this.router.navigate(['pages/login']); return Observable.of(false); } });

The route works but only 1 time. Not sure if it's possible to make this action repeat (the service will resend the check to the service when the request is finish, of course I should make a little timeout for it)?

vuquanghoang
  • 370
  • 2
  • 5
  • 15

1 Answers1

5

Actually I don't think that's a good practice to check the session timeout. The canActivate guard is a simple check for example that the user has permission to open this route or not. For checking the session timeout I would put a timer into your service which will call the backend for the information. I would also use HttpInterceptor to check the errors from the backend. When your backend will send an error message with code 401 UNAUTHORIZED it will navigate the user to the login page as you can see the example below.

@Injectable()
export class UnauthorizedInterceptor implements HttpInterceptor {

    constructor(private router: Router) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).catch(err => {
            if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                    this.router.navigate(['/Login']);
                }
            }
            return Observable.throw(err.statusText);
        });
    }
}
Mate Zabo
  • 1,616
  • 2
  • 22
  • 31