Angular 9: Guard which calls API to check if session did not expire

271 views Asked by At

On some pages in my Angular app, I want to validate the session is not expired.

I have token in local storage, so in AuthService I have:

isUserAuthenticated(): Observable<boolean> {
    const token = localStorage.getItem('token');
    if(token) {

      return this.http.get<any>(this.apiUrl.getUser, {headers: {'X-Auth-Token': token}}).pipe(
        tap(data => {return true}),
        catchError(this.handleError)
      ); 
    } else {
      return of(false);
    }
  }

First of all: is above code correct?

How should my canActivate function look like?

I tried this:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean>|boolean {
    return this.authService.isUserAuthenticated().pipe(map(User => {
      return (User) ? true : false;
    }));
}

but it gives me error when token is expired.

0

There are 0 answers