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

相关内容

热门资讯

透视app!哈糖大菠萝有挂5个... 透视app!哈糖大菠萝有挂5个常用方法,wepoker安装教程“解谜开挂透视挂辅助app”哈糖大菠萝...
透视了解!werplan有挂,... 透视了解!werplan有挂,wepoker可以设置房间“解迷开挂透视挂辅助方法”1、操作简单,无需...
透视好友房!wepoker破解... 透视好友房!wepoker破解是真的还是假的,约局吧如何查看是否有挂“解谜开挂透视挂辅助方法”1、完...
透视脚本!wpk辅助器是真的,... 透视脚本!wpk辅助器是真的,poker辅助器免费安装“曝光开挂透视挂辅助软件”1、完成poker辅...
透视脚本!wepoker软件安... 透视脚本!wepoker软件安装包,cloudpoker透视挂“关于开挂透视挂辅助工具”1、进入到w...
透视脚本!hhpoker透视脚... 透视脚本!hhpoker透视脚本视频,德普之星透视“推荐开挂透视挂辅助方法”;1、下载好hhpoke...
透视安装!约局吧德州可以透视,... 透视安装!约局吧德州可以透视,wepoker透视是真的“曝光开挂透视挂辅助软件”1、首先打开约局吧德...
透视好友房!hhpoker买挂... 透视好友房!hhpoker买挂,wpk真的有透视嘛“教你开挂透视挂辅助方法”1、操作简单,无需注册,...
透视数据!哈糖大菠萝挂,wep... 透视数据!哈糖大菠萝挂,wepoker透视挂辅助“解谜开挂透视挂辅助神器”1、wepoker透视挂辅...
透视美元局!wepoker线上... 透视美元局!wepoker线上大神,newpoker可以安装脚本“科普开挂透视挂辅助教程”1、new...