1
|
import { filter, switchMap, tap } from 'rxjs/operators';
|
2
|
import { AuthService } from './../services/auth.service';
|
3
|
import { Injectable } from '@angular/core';
|
4
|
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
|
5
|
import { Observable } from 'rxjs';
|
6
|
|
7
|
@Injectable({
|
8
|
providedIn: 'root'
|
9
|
})
|
10
|
export class AuthGuard implements CanActivate {
|
11
|
|
12
|
constructor(private auth: AuthService, private router: Router) { }
|
13
|
|
14
|
canActivate(
|
15
|
route: ActivatedRouteSnapshot,
|
16
|
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
|
17
|
|
18
|
return this.auth.isDoneLoading$.pipe(
|
19
|
filter(isDone => isDone),
|
20
|
switchMap(_ => this.auth.isAuthenticated$),
|
21
|
tap(isAuthenticated => isAuthenticated || this.auth.login(state.url)),
|
22
|
);
|
23
|
}
|
24
|
}
|