Angular中用于限制用户访问特定路由的防护无法正常工作。
创始人
2024-10-31 20:02:02
0
  1. 确保在路由定义中正确配置了AuthGuard。

例如,在app-routing.module.ts中定义路由:

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
  ...
];
  1. 确保AuthGuard中的canActivate()方法返回一个Observable或Promise。

例如,在auth.guard.ts中定义AuthGuard:

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean {
    return this.authService.isLoggedIn()
      .pipe(
        map((isLoggedIn: boolean) => {
          if (!isLoggedIn) {
            this.router.navigate(['/login']);
            return false;
          }
          return true;
        })
      );
  }
}
  1. 确保AuthService中的isLoggedIn()方法返回一个Observable或Promise。

例如,在auth.service.ts中定义AuthService:

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  // use BehaviorSubject to keep track of login state
  private loggedIn = new BehaviorSubject(false);

  constructor() { }

  isLoggedIn(): Observable {
    // return BehaviorSubject as an Observable
    return this.loggedIn.asObservable();
  }

  login() {
    this.loggedIn.next(true);
  }

  logout() {
    this.loggedIn.next(false);
  }
}

在login.component.ts中处理用户登录:

export class LoginComponent implements OnInit {
  constructor(private authService: AuthService) {}

  ngOnInit() {}

  login() {
    // authenticate user and set isLoggedIn to true
    this.authService.login();
  }
}

在navbar.component.ts中处理用户注销:

export class NavbarComponent implements OnInit {
  constructor(private authService: AuthService) {}

  ngOnInit() {}

  logout() {
    // log out user and set isLoggedIn to false
    this.authService.logout();
  }
}

相关内容

热门资讯

透视揭露"hhpok... 透视揭露"hhpoker可以控制吗"本来真的是有辅助教程(哔哩哔哩)1、完成hhpoker可以控制吗...
透视教你"wepok... 透视教你"wepoker怎么提高运气"竟然真的是有辅助app(哔哩哔哩)1、wepoker怎么提高运...
透视解密"德州透视h... 透视解密"德州透视hhpoker"其实真的有辅助挂(哔哩哔哩)德州透视hhpoker能透视中分为三种...
透视推荐"wepok... 透视推荐"wepoker永久免费脚本"真是真的是有辅助技巧(哔哩哔哩)1、wepoker永久免费脚本...
透视详情"wepok... 透视详情"wepoker怎么挂飞机"本来真的是有辅助工具(哔哩哔哩)1、首先打开wepoker怎么挂...
透视推荐"wepok... 透视推荐"wepoker黑侠辅助器"原来真的是有辅助挂(哔哩哔哩)1、玩家可以在wepoker黑侠辅...
透视辅助"约局吧是否... 透视辅助"约局吧是否有挂"确实存在有辅助app(哔哩哔哩)1、约局吧是否有挂破解器简单,约局吧是否有...
透视分享"德州局怎么... 透视分享"德州局怎么透视"一直真的是有辅助挂(哔哩哔哩)1.德州局怎么透视 选牌创建新账号,点击进入...
透视总结"wpk模拟... 透视总结"wpk模拟器是什么"本来是真的辅助神器(哔哩哔哩)wpk模拟器是什么能透视中分为三种模型:...
透视了解"wepok... 透视了解"wepoker轻量版辅助"真是存在有辅助脚本(哔哩哔哩)在进入wepoker轻量版辅助软件...