Angular 2 AuthGuard Service with redirect?

前端 未结 5 1155
南旧
南旧 2020-12-05 22:46

I have an application that I am building that implements CanActivate on the dashboard route. It works fine accept on page reload, I check a flag in the user service to see i

相关标签:
5条回答
  • 2020-12-05 23:22

    in AuthGuard Do this

    @Injectable()
    
    export class AuthGuard implements CanActivate {
    
    auth: any = {};
    
    constructor(private authService: AuthService, private router: Router) {
    
    }
    
    canActivate() {
        if (/*user is logged in*/) {
            this.router.navigate(['/dashboard']);
            return true;
        }
        else {
            this.router.navigate(['/Login']);
        }
        return false;
    }
    }
    
    0 讨论(0)
  • 2020-12-05 23:36

    Here's how to correctly handle redirects in a guard by using an UrlTree

    @Injectable({
      providedIn: 'root'
    })
    export class AuthGuard implements CanActivateChild {
      constructor(
        private authService: AuthService,
        private logger: NGXLogger,
        private router: Router
      ) {}
    
      canActivateChild(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> {
    
        return this.authService.isLoggedIn().pipe(
          map(isLoggedIn => {
            if (!isLoggedIn) {
              return this.router.parseUrl('/login');
            }
    
            return true;
          })
        );
      }
    }
    

    Big thanks to Angular In Depth for the explanation!

    0 讨论(0)
  • 2020-12-05 23:39

    I actually changed my service to this and it works:

    import { Injectable }             from '@angular/core';
    import { CanActivate, Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot }    from '@angular/router';
    import { AuthService }            from './auth.service';
    import {UserService} from "./user.service";
    
    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private authService: AuthService, private router: Router, private userService: UserService) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    
    
    
        if (this.authService.isLoggedIn){
          console.log('ATUH GUARD SAYD THEY ARE ALREADY LOGGED IN!');
          return true;
    
    
        }else {
    
    
          this.userService.getUser().subscribe((user) => {
    
            console.log('AUTH GUARD GETTING USER', user);
    
            if (user._id) {
            this.authService.isLoggedIn = true;
            // Store the attempted URL for redirecting
            this.authService.redirectUrl = state.url;
            this.router.navigate(['/dashboard']);
            return true;
            }else{
              console.log('Validation Failed.');
              localStorage.clear();
              this.router.navigate(['/login']);
              return false;
            }
    
    
          }, (error) => {
            console.log('There was an error.');
            this.router.navigate(['/login']);
            return false
    
          });
    
        }
    
    
      }
    }
    
    0 讨论(0)
  • 2020-12-05 23:39

    You can now return a UrlTree from an AuthGuard, or a boolean true / false.

    Kind of amazed nobody has mentioned this yet! Sorry no example right now, but the idea is pretty simple.

    0 讨论(0)
  • 2020-12-05 23:44

    I solved it like this and used it in my AuthGuard

    isLoggedIn(): Observable<boolean> {
    return this.afAuth.authState
      .pipe(
        take(1),
        map(user => {
            return !!user;
          },
          () => {
            return false;
          }
        ),
        tap(loggedIn => {
            if (!loggedIn) {
              this.router.navigate(['/']);
            }
          }
        ));
    }
    
    0 讨论(0)
提交回复
热议问题