Skip to content

Instantly share code, notes, and snippets.

@artworkad
Created February 21, 2017 11:31
Show Gist options
  • Save artworkad/a5687f324d8b4424e62ca3d4e3d1eb97 to your computer and use it in GitHub Desktop.
Save artworkad/a5687f324d8b4424e62ca3d4e3d1eb97 to your computer and use it in GitHub Desktop.
Building an Authentication Observable Data Service - auth-guard.service.ts
import {Injectable} from '@angular/core';
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {AuthService} from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService,
private router: Router) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.authService.authInfo$.map(authInfo => {
if (!authInfo.isLoggedIn()) {
this.router.navigate(['/']);
}
return authInfo.isLoggedIn();
});
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.canActivate(route, state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment