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透视挂效果如何这款游戏是可以开挂的,软件加【添加微信客服136704302】确实...
玩家必看科普“wepoker透... 玩家必看科普“wepoker透视开挂挂教程”开挂辅助器(透视)扑克教程是一款可以让一直输的玩家,快速...
传递经验“wepoker透视挂... 您好:wepoker透视挂真的吗这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
揭秘几款“wepoker透视脚... 揭秘几款“wepoker透视脚本连接”开挂辅助插件(透视)2026新版是一款可以让一直输的玩家,快速...
玩家必备攻略“微扑克发牌机制”... 玩家必备攻略“微扑克发牌机制”开挂辅助平台(透视)科技教程是一款可以让一直输的玩家,快速成为一个“必...
发现一款“wepkoer开挂透... 发现一款“wepkoer开挂透视方法”开挂辅助器(透视)必赢教程是一款可以让一直输的玩家,快速成为一...
推荐一款“wepoker私人局... 您好:wepoker私人局透视挂真的吗的软件,软件加客服确实是有挂的,很多玩家在这款游戏中打牌都会发...
实测必看“wepoker开挂透... 您好:wepoker开挂透视方法这款游戏是可以开挂的,软件加【添加微信客服136704302】确实是...
推荐十款“wepoker开挂软... >>>您好:,软件加微信【添加136704302】确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
每日必看教程“wepoker透... 每日必看教程“wepoker透视脚本配置”开挂辅助神器(透视)存在挂教程是一款可以让一直输的玩家,快...