0
@Injectable()

export class AuthGuard implements CanActivate {

    constructor(private authService: AuthService,private router: Router){}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        const isAuth = this.authService.checkAuth()
        if (!isAuth){
            this.router.navigate(['/login'])
        }
        return isAuth;
    }
}

I dont understand where i`m wrong but isAuth is always false if i console.log it.

Edit

  checkAuth(){
return this.loggedIn.asObservable();

}

loginUser(email: string, password:string){
    const user: User = {email: email, password: password}
    this.http.post<{token: string}>('http://localhost:3000/api/auth/login', user).subscribe( result => {
    const token = result.token;
    this.token = token
    this.loggedIn.next(true)
    this.router.navigateByUrl('/admin')
    })
  }

This is working fine but, it not seems a good practice.. and i was tryn to write better code lines.

    @Injectable()
export class AuthGuard implements CanActivate {
auth: Subscription;
isAuth: boolean;
    constructor(private authService: AuthService,private router: Router){}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        this.auth = this.authService.checkAuth().subscribe(result=>{
            this.isAuth = result
        })
        if (!this.isAuth){
            this.router.navigate(['/login'])
        }
        return this.isAuth;
    }
}
NoReason
  • 1
  • 2

1 Answers1

1

@Kardon63 You're right but I think the method to call is getValue() instead of value.

Therefore you have to change your checkAuth method and write :

checkAuth(){
  return this.loggedIn.getValue();
}

Check this post : https://stackoverflow.com/a/37089997/6444705

Emilien
  • 2,701
  • 4
  • 15
  • 25