NGRX 是一个用于 Angular 应用的状态管理库,它基于 Redux 模式,提供了可预测的状态容器。在实现路由器防护时,NGRX 可以用来管理应用的状态,确保用户在未授权的情况下无法访问某些路由。
NGRX: 是一个状态管理库,它使用 Redux 的概念,如 actions、reducers 和 selectors 来管理 Angular 应用的状态。
路由器防护: 在 Angular 中,路由器防护用于控制用户是否可以导航到某个路由。常见的防护类型包括 CanActivate
、CanDeactivate
等。
// auth.reducer.ts
export interface AuthState {
isAuthenticated: boolean;
}
export const initialState: AuthState = {
isAuthenticated: false,
};
// auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import { selectIsAuthenticated } from './auth.selectors';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private store: Store, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> {
return this.store.select(selectIsAuthenticated).pipe(
map(isAuthenticated => {
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
})
);
}
}
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] },
// ...其他路由
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
问题: 用户在未登录状态下尝试访问受保护的路由。
原因: 用户可能通过直接输入 URL 或刷新页面尝试访问受保护的路由。
解决方法: 使用 AuthGuard
来检查用户的认证状态,并在用户未认证时重定向到登录页面。
// auth.effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { AuthService } from './auth.service';
import { login, loginSuccess, loginFailure } from './auth.actions';
@Injectable()
export class AuthEffects {
constructor(private actions$: Actions, private authService: AuthService) {}
login$ = createEffect(() =>
this.actions$.pipe(
ofType(login),
switchMap(action =>
this.authService.login(action.credentials).pipe(
map(user => loginSuccess({ user })),
catchError(error => of(loginFailure({ error })))
)
)
)
);
}
通过上述步骤,你可以使用 NGRX 来实现一个有效的路由器防护机制,确保只有认证用户才能访问特定的路由。
领取专属 10元无门槛券
手把手带您无忧上云