Skip to content

Instantly share code, notes, and snippets.

@ibnumalik
Last active September 13, 2022 03:04
Show Gist options
  • Save ibnumalik/fbdf92ee0e2fe2066fe241b2bcc2db89 to your computer and use it in GitHub Desktop.
Save ibnumalik/fbdf92ee0e2fe2066fe241b2bcc2db89 to your computer and use it in GitHub Desktop.
(angular) Auth guard to check if user is logged in
import { Injectable } from '@angular/core';
import { CanLoad, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthQuery } from './state/auth.query';
import { tap, take } from 'rxjs/operators';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanLoad {
constructor(private authQuery: AuthQuery, private router: Router) {}
canLoad(): Observable<boolean> {
return this.authQuery.isLoggedIn$.pipe(
take(1),
tap((isLoggedIn) => {
if (!isLoggedIn) {
return this.router.navigateByUrl('/');
}
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment