简体   繁体   中英

Angular AuthGuard canActivate

AuthGuard blocks everything it should. But one undesirable thing happens when I return true. I get a "test" in the console, but instead of letting me in /test, it redirects me to /. Why? It's RouterModule in app.module.ts:

    RouterModule.forRoot([
      { path: 'test', component: HomeComponent, canActivate: [AuthGuard] },
      { path: 'account/register', component: RegisterComponent }
], { relativeLinkResolution: 'legacy' })

And it's AuthGuard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private _authService: AuthService, private _cookieService: CookieService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    const tokenExists: boolean = this._cookieService.check("token");
    if (tokenExists == true) {
      const token = this._cookieService.get("token");
      this._authService.isAuthenticated(token).subscribe(data => {
        if (data as any == true) {
          console.log("test");
          return true;
        }
        else if (data as any == false) {
          this.router.navigate(['account/register']);
          return false;
        }
        else {
          this.router.navigate(['account/register']);
          return false;
        }
      });
    }
    else {
      this.router.navigate(['account/register']);
      return false;
    }
  }
}

Why is this happening?

You should return subscribe scope too. refator as

 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { const tokenExists: boolean = this._cookieService.check("token"); if (tokenExists == true) { const token = this._cookieService.get("token"); return this._authService.isAuthenticated(token).subscribe(data => { if (data as any == true) { console.log("test"); return true; } else if (data as any == false) { this.router.navigate(['account/register']); return false; } else { this.router.navigate(['account/register']); return false; } }); } else { this.router.navigate(['account/register']); return false; } }

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