AngularRouter路由守卫CanActivate始终返回false
创始人
2024-10-29 06:00:56
0

问题的原因是因为CanActivate守卫函数必须返回一个布尔对象,以允许或拒绝导航到相应的组件。如果该函数返回false,导航将被取消,并且将停留在当前页面。

下面是解决该问题的示例:

在路由定义中添加CanActivate守卫函数,在该函数中处理认证和授权逻辑,并根据结果返回true或false。

例如:

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

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    }

    // 认证失败,重定向到登录页面
    this.router.navigate(['/login']);
    return false;
  }
}

然后在路由定义中使用AuthGuard守卫函数,例如:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

const appRoutes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

这就可以解决CanActivate始终返回false的问题,并在路由守卫函数中处理认证和授权逻辑。

相关内容

热门资讯

透视透视!德普之星怎么设置埋牌... 透视透视!德普之星怎么设置埋牌(透视)新财神正版辅助挂(其实真的有辅助安装)-哔哩哔哩1、不需要AI...
记者获悉!hhpoker透视脚... 记者获悉!hhpoker透视脚本视频(透视)爱玩联盟辅助软件(都是有辅助app)-哔哩哔哩一、爱玩联...
日前!wejoker辅助软件视... 日前!wejoker辅助软件视频(透视)微乐贵阳麻将辅助(一直有辅助下载)-哔哩哔哩1、打开软件启动...
据监测!we-poker靠谱吗... 据监测!we-poker靠谱吗(透视)威信茶馆大贰破解(本来是有辅助app)-哔哩哔哩1、每一步都需...
做出回应!hhpoker哪个俱... 做出回应!hhpoker哪个俱乐部靠谱(透视)捉住捣蛋鸡作必弊(真是存在有辅助插件)-哔哩哔哩1、捉...
透视游戏!德州透视竞技联盟(透... 透视游戏!德州透视竞技联盟(透视)哈灵脚本辅助(本来真的是有辅助平台)-哔哩哔哩哈灵脚本辅助破解侠是...
现有说明如下!aapoker真... 您好,福建天天开心辅助器是真的码这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
来临!wepokerplus透... 来临!wepokerplus透视脚本免费(透视)广东雀神祈福辅助器(本来是真的辅助安装)-哔哩哔哩暗...
透视有挂!hhpoker是真的... 透视有挂!hhpoker是真的还是假的(透视)广西老友玩有破解(一直真的有辅助平台)-哔哩哔哩1、上...
推出新举措!we poker游... 推出新举措!we poker游戏下(透视)微信小程序开心泉州辅助器(好像是有辅助工具)-哔哩哔哩1、...