Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Modifying 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
// SINCE OUR 'authService.user' IS OF TYPE 'Observable'
// WE MUST USE 'subscribe' TO GET VALUE OF 'user'
this.authService.user.subscribe((user) => {
if (!user) {
// when the user is not logged in,
// instead of just returning false
// inject router and redirect to '/login' or any other view
this.router.navigate(['/login'], {
// note: this queryParams returns the current URL
// that we can have in 'return' parameter,
// so when the '/login' page opens,
// this param tell us from where it comes
// read-more to understand better👇👇
queryParams: {
return: state.url
}
});
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.