简体   繁体   中英

Angular 5 canActivate always return to login page for specific route

I'm trying to secure my app from unauthorized users, by defining routes guard and assigning canActivate to each wanted-to-be-secure route. Everything is going fine on those routes, for example when someone want to access route from url it will redirect automatically to login page unless if he/she is logged in then the app will redirect to the specific route. But there is one route, when user is logged in it always return to the login page. This issue occurs on the route '/verify/:idC' , what should I do?

routing.ts:

{ path: 'verify/:idC', component: VerifyRoleComponent, canActivate: [AuthGuard] },

auth-guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthService } from '../auth/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }

}

auth.service.ts:

@Injectable()
export class AuthService {

  isLoggedIn = false;

  constructor() { }

  // store the URL so we can redirect after logging in
  redirectUrl: string;

  login(): Observable<boolean> {
    return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
  }

  logout(): void {
    this.isLoggedIn = false;
  }

}

verify-component.ts:

@Component({
  selector: 'app-verify-role',
  templateUrl: './verify-role.component.html',
  styleUrls: ['./verify-role.component.scss']
})
export class VerifyRoleComponent implements OnInit {

  auth: Auth;

  constructor(private credService: CredentialService, private authService: AuthService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {    
    const id = this.route.snapshot.paramMap.get('idC');
    console.log(id) ;

    this.route.paramMap
      .switchMap((params: ParamMap) => 
        this.credService.getAccountId(params.get('idC')))
          .subscribe(res => {
            this.auth = res;
            console.log(this.auth);
            if (res.role.toString() == "User"){
              let idC = res.account;
              this.loginUser(idC);
            } else {}
          }, err => {
            console.log(err);
        });
  }

  loginUser(idC:string) {
    this.authService.login().subscribe(() => {
      if (this.authService.isLoggedIn) {
        let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/profile/'+idC;
        this.router.navigate([redirect]);
      }
    });
  }

}

我认为您必须在this.router.navigate(['/login']);之前添加一个else this.router.navigate(['/login']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM