Angular 2 AuthGuard Service with redirect?

前端 未结 5 1161
南旧
南旧 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: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
    
          });
    
        }
    
    
      }
    }
    

提交回复
热议问题