File

src/app/core/auth.guard.ts

Index

Methods

Constructor

constructor(auth: AuthService, router: Router)
Parameters :
Name Type Optional
auth AuthService No
router Router No

Methods

canActivate
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot)
Parameters :
Name Type Optional
next ActivatedRouteSnapshot No
state RouterStateSnapshot No
Returns : Observable | Promise | boolean
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router
} from '@angular/router';
import { Observable } from 'rxjs';
import { map, take, tap } from 'rxjs/operators';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private auth: AuthService, private router: Router) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth.user.pipe(
      take(1),
      map(user => !!user),
      tap(loggedIn => {
        if (!loggedIn) {
          console.log('access denied');
          this.router.navigate(['/sigin']);
        }
      })
    );
  }
}

result-matching ""

    No results matching ""