Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create AuthGuardService
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
// the Router call canActivate() method,
// if canActivate is registered in Routes[]
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
// here we check if user is logged in or not
// the authService returs user object, or
// it returns undefined/null when user is not logged in
if (!this.authService.user) {
// just return false - if user is not logged in
return false;
} else {
// just return true - if user is logged in
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.