Angular 7的路由保护不起作用
创始人
2024-10-17 01:00:16
0

要解决“Angular 7的路由保护不起作用”的问题,你可以按照以下步骤进行操作:

  1. 确保你已经正确配置了路由保护。在Angular应用中,你可以使用CanActivate守卫来实现路由保护。例如,你可以创建一个名为AuthGuard的守卫类,并在路由中指定该守卫类来保护特定的路由。
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}
  1. 确保你已经将AuthGuard守卫添加到需要保护的路由中。在你的路由配置文件(通常是app-routing.module.ts)中,将AuthGuard守卫添加到需要保护的路由中的canActivate属性中。
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  // 其他路由...
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  1. 确保你的AuthService中的isLoggedIn()方法能够正确判断用户是否已登录。该方法应该返回一个布尔值来表示用户的登录状态。
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  // 模拟用户登录状态,你可以根据实际情况进行修改
  private loggedIn = false;

  constructor() { }

  isLoggedIn(): boolean {
    return this.loggedIn;
  }

  login() {
    this.loggedIn = true;
  }

  logout() {
    this.loggedIn = false;
  }
}
  1. 确保你在登录成功后调用了AuthService中的login()方法,并在注销时调用了logout()方法。

通过以上步骤,你应该能够实现Angular 7中的路由保护。当用户未登录时,访问受保护的路由时会被重定向到登录页面。而当用户已登录时,才能成功访问受保护的路由。

相关内容

热门资讯

盘点几款!hhpoker德州牛... 盘点几款!hhpoker德州牛仔视频,hhpoker是正规的吗,力荐教程(有挂透明);实战中需综合运...
热点推荐!hhpoker德州真... 这是一款非常优秀的hhpoker德州真的假的 ia辅助检测软件,能够让你了解到hhpoker德州真的...
传递经验!wepoker辅助是... 传递经验!wepoker辅助是真的吗,wpk模拟器多开,力荐教程(有挂方法)1、玩家可以在wepok...
盘点一款!wepokerplu... 此外,数据分析德州(wepokerplus透视脚本免费)辅助神器app还具备辅助透视行为开挂功能,通...
最新通报!wejoker内置辅... 最新通报!wejoker内置辅助,红龙poker辅助,大神讲解(有挂软件)是由北京得wejoker内...
一分钟了解!wepoker私人... 一分钟了解!wepoker私人局外卦,wepoker安装教程,AI教程(有挂方法)这是由厦门游乐互动...
2分钟细说!佛手大菠萝有挂吗,... 2分钟细说!佛手大菠萝有挂吗,德普之星有辅助软件吗,安装教程(有挂透视)准备好在德普之星有辅助软件吗...
大家学习交流!wepoker有... 大家学习交流!wepoker有脚本吗,wepoker插件下载,2025新版教程(有挂辅助)准备好在w...
新手必备!werplan透视挂... 新手必备!werplan透视挂,wepoker透视是真的吗,wpk教程(有挂辅助);最新版2024是...
解密关于!hhpoker是真的... 解密关于!hhpoker是真的还是假的,wepoker的辅助器,实用技巧(有挂软件);hhpoker...