如何使用新的 CanActivateFn 而不是已弃用的 CanActivate 在 Angular auth Guard 中实现由 auth reducer 管理的状态?

问题描述 投票:0回答:1
// auth.guard.ts
export class AuthGuard implements CanActivate {

  constructor(private store: Store<fromAuth.AuthState>, private router: Router) {}

  canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(fromAuth.selectUser), // Select user from the auth state
      map((user) => {
        if (user) {
          return true; // User is logged in, allow access to the route
        } else {
          this.router.navigate(['/login']); // User is not logged in, navigate to login page
          return false;
        }
      })
    );
  }
}

我正在使用 ngrx 来管理身份验证状态并在身份验证防护中使用它。 CanActivate 已弃用,我想使用 CanActivateFn 来保护从身份验证缩减程序 fromAuth 到身份验证状态的路由。

angular routes ngrx auth-guard canactivate
1个回答
0
投票

要调整现有的 AuthGuard 逻辑以使用 CanActivateFn,您需要执行以下步骤:

  1. 更新您的导入语句以包含 CanActivateFn。
  2. 使用提供的存储和路由器创建 CanActivateFn 函数。

以下是如何重构 AuthGuard 类以使用

CanActivateFn
:

  1. 更新导入语句:

确保您拥有新功能防护实施所需的导入。

import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { fromAuth } from '../path-to-auth-state'; // Adjust the path to your auth state

2.使用

authGuard
创建
CanActivateFn
函数:

export const authGuard: CanActivateFn = () => {
  const store = inject(Store<fromAuth.AuthState>);
  const router = inject(Router);

  return store.pipe(
    select(fromAuth.selectUser), // Adjust the selector to match your state
    map((user) => {
      if (user) {
        return true; // User is logged in, allow access to the route
      } else {
        router.navigate(['/login']); // User is not logged in, navigate to login page
        return false;
      }
    })
  );
};
  1. 在路线配置中使用
    authGuard

在路由模块中,用新的

canActivate
函数替换旧的
authGuard
防护。

import { Routes } from '@angular/router';
import { authGuard } from './path-to-auth-guard'; // Adjust the path to your auth guard

const routes: Routes = [
  {
    path: 'protected-route',
    component: ProtectedComponent,
    canActivate: [authGuard]
  },
  // Other routes
];
  1. 确保您的身份验证状态和选择器设置正确:

确保您的

fromAuth.selectUser
选择器和
AuthState
在您的 NgRx 设置中正确定义。

// auth.selectors.ts
import { createSelector } from '@ngrx/store';
import { AuthState } from './auth.reducer'; // Adjust the path to your auth reducer

export const selectAuthState = (state: AppState) => state.auth;

export const selectUser = createSelector(
  selectAuthState,
  (state: AuthState) => state.user
);
© www.soinside.com 2019 - 2024. All rights reserved.