簡體   English   中英

如果我在登錄時刷新頁面,Guard 會將我重定向到登錄頁面

[英]If I refresh the page when I'm logged in, the Guard redirects me to the login page

如果我在登錄時刷新頁面,Guard 會將我重定向到登錄頁面。 只有當用戶真正退出時,有沒有辦法重定向到登錄頁面? 我使用前端作為 angular(版本:12.2.13)和后端作為 firebase。

auth.guard.ts

import { Injectable } from "@angular/core";
import { ActivatedRouteSnapshot, CanActivate, Router, 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){
    if(this.authService.isAuth()){
        return true;
    } else {
        this.router.navigate(['/auth']);
    }
  }
}

當用戶登錄應用程序時,用戶的狀態應該保存在 sessionStorage 或 Redux 中。然后必須定義一個 AuthGuard 服務。最后必須將 AuthGuard 添加到每個 Routes。

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

  constructor(private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    
    const userLoginStatus = sessionStorage.getItem("userLogin");
    const IsUserLogin: boolean | null = userLoginStatus ? JSON.parse(userLoginStatus) : null;
    
    if ( IsUserLogin ) {
      return true
    }
    else {
      this.router.navigateByUrl("/");
      return false
    }
    
  }
  
}

帶有受 AuthGuard 保護的本地路由的路由

import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },

    // home route protected by auth guard
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing = RouterModule.forRoot(appRoutes);

如果用戶未登錄,AuthGuard 將重定向到登錄頁面

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM