import { Injectable } from '@angular/core' ; import { Router , CanActivate , ActivatedRouteSnapshot , RouterStateSnapshot } from '@angular/router' ; import { Store , select } from '@ngrx/store' ; import { Observable } from 'rxjs' ; import { filter , map , take } from 'rxjs/operators' ; @ Injectable ( { providedIn : 'root' } ) export class AuthGuard implements CanActivate { constructor ( private readonly router , private readonly store ) { } canActivate ( route , routerState ) { const { returnUrl = routerState . url } = route . queryParams ; this . store . dispatch ( { type : '[Auth] Check Auth Requested' } ) ; return this . store . pipe ( select ( state => state ) , map ( ( state ) => ( state . currentUser ) ? state : Object . assign ( { } , state , { loading : false } ) ) , filter ( ( state ) => state . loading === false ) , map ( ( state ) => { if ( state . authCheck ) { return true ; } this . router . navigate ( [ '/auth' ] , { queryParams : { returnUrl } } ) ; return false ; } ) , take ( 1 ) ) ; } }