import { Injectable } from '@angular/core'; import { CanLoad, Route, UrlSegment, Router } from '@angular/router'; import { Observable, of } from 'rxjs'; import { take, tap, switchMap } from 'rxjs/operators'; import { UserService } from '../services/user.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanLoad { constructor(private authService: UserService, private router: Router) {} canLoad( route: Route, segments: UrlSegment[] ): Observable | Promise | boolean { return this.authService.userIsAuthenticated.pipe( take(1), switchMap(isAuthenticated => { if (!isAuthenticated) { console.log('isAuthenticated'+isAuthenticated); return this.authService.autoLogin(); } else { return of(isAuthenticated); } }), tap(isAuthenticated => { if (!isAuthenticated) { this.router.navigateByUrl('/auth'); } }) ); } }