Angular 2中未登录用户直接访问页面的鉴权与跳转实现问询
Hey there! Let's walk through how to handle these authentication redirect scenarios in Angular 2 clearly:
The cleanest way to handle this is using Angular's CanActivate route guard. Here's the play-by-play:
- First, create an authentication service to track the user's login state. This service will have methods to check and update authentication status:
import { Injectable } from '@angular/core'; @Injectable() export class AuthService { // Track login state (persist to localStorage to survive page refreshes) private isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'; setLoginState(state: boolean) { this.isLoggedIn = state; localStorage.setItem('isLoggedIn', state.toString()); } isUserLoggedIn(): boolean { return this.isLoggedIn; } }
- Next, build a route guard that uses this service to validate access:
import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, 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.isUserLoggedIn()) { return true; // Allow access to the route } else { // Redirect to login page if not authenticated this.router.navigate(['/login']); return false; } } }
- Finally, attach this guard to your homepage route in the routing module:
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 }, // Other public routes... ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [AuthGuard, AuthService] }) export class AppRoutingModule {}
Now, any unlogged user trying to access the homepage will be automatically sent to the login page.
We'll reuse the same AuthGuard here, plus add a small improvement to redirect users back to their intended page after login:
- Update your route configuration to apply the guard to the Dashboard (and other protected routes):
const routes: Routes = [ { path: '', component: HomeComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent }, { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, // Other protected routes... ];
- Modify the
AuthGuardto capture the original URL the user was trying to access:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (this.authService.isUserLoggedIn()) { return true; } else { // Store the target URL so we can redirect after login this.authService.setRedirectUrl(state.url); this.router.navigate(['/login']); return false; } }
- Add redirect URL handling to your
AuthService:
private redirectUrl: string = ''; setRedirectUrl(url: string) { this.redirectUrl = url; } getRedirectUrl(): string { return this.redirectUrl; }
- In your
LoginComponent, update the login success logic to redirect to the stored URL (or homepage if none exists):
import { Component } from '@angular/core'; import { AuthService } from './auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html' }) export class LoginComponent { constructor(private authService: AuthService, private router: Router) {} onLoginSuccess() { this.authService.setLoginState(true); const redirectUrl = this.authService.getRedirectUrl(); // Send user to their original target or homepage this.router.navigate([redirectUrl || '/']); // Clear the redirect URL after use this.authService.setRedirectUrl(''); } }
Now, if a user tries to jump straight to /dashboard without logging in, they'll be sent to login. Once they authenticate successfully, they'll land right on the Dashboard instead of the homepage—way better for user experience!
内容的提问来源于stack exchange,提问作者Shiva Kumar

