首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular AuthGuard canActivate

Angular AuthGuard canActivate
EN

Stack Overflow用户
提问于 2021-03-07 03:34:04
回答 1查看 129关注 0票数 0

AuthGuard阻止了它应该阻止的一切。但是当我返回true时,就会发生一件令人不快的事情。我在控制台中得到一个“测试”,但它没有让我进入/test,而是将我重定向到/。为什么?这是app.module.ts中的RouterModule:

代码语言:javascript
复制
    RouterModule.forRoot([
      { path: 'test', component: HomeComponent, canActivate: [AuthGuard] },
      { path: 'account/register', component: RegisterComponent }
], { relativeLinkResolution: 'legacy' })

这就是AuthGuard:

代码语言:javascript
复制
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;
    }
  }
}

为什么会发生这种情况?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-07 03:52:24

你也应该返回订阅范围。refator

代码语言:javascript
复制
 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;
    }
  }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66509859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档