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的问题,并在路由守卫函数中处理认证和授权逻辑。

相关内容

热门资讯

玩家必备攻略!wepoker透... 玩家必备攻略!wepoker透视苹果系统,wejoker手机版透视脚本,真是真的是有挂(有挂教学)玩...
指导大家!聚星ai辅助工具收费... 指导大家!聚星ai辅助工具收费多少,wepokerplus透视脚本免费,一直有挂(有挂猫腻)1、打开...
记者发布!德普之星透视辅助插件... 记者发布!德普之星透视辅助插件,wepoker私人局辅助挂,切实存在有挂(揭秘有挂)1、操作简单,无...
一分钟了解!菠萝德州透视脚本,... 一分钟了解!菠萝德州透视脚本,epoker透视底牌,本来真的是有挂(有挂分析)1、很好的工具软件,可...
盘点十款!德州局透视脚本免费版... 盘点十款!德州局透视脚本免费版下载手机版,德州机器人代打脚本,切实有挂(真实有挂)1)辅助插件:进一...
玩家交流!wepoker开脚本... 玩家交流!wepoker开脚本视频,hhpoker真能买到挂吗,真是存在有挂(竟然有挂)1、首先打开...
重大通报!wepoker透视挂... 重大通报!wepoker透视挂底牌,pokemmo辅助器手机版下载,都是真的是有挂(有挂详情)1、首...
热点推荐!hhpoker免费透... 热点推荐!hhpoker免费透视脚本,aapoker安装包怎么使用,总是是有挂(真的有挂)1、下载好...
大神推荐!哈糖大菠萝软件下载,... 大神推荐!哈糖大菠萝软件下载,we poker游戏下,总是是有挂(有挂细节)1、上手简单,内置详细流...
一分钟教你!aa poker辅... 一分钟教你!aa poker辅助包,pokeplus脚本,好像真的是有挂(有挂讲解);1、完成辅助器...