首页 > 解决方案 > Angular如何修复ssr auth guard故障以在刷新时显示登录页面一秒钟?

问题描述

我讨厌 auth.guard.ts :

import { Injectable } from '@angular/core';
import {  CanActivateChild, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AuthService } from '../services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivateChild {
  constructor(public auth: AuthService, public router: Router) {}
  canActivateChild(): Observable<boolean> {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['b2b/auth/login']);
      return of(false);
    }
    return of(true);
  }
}

如果人员未登录,则返回登录页面。当我在本地机器上编码时,它应该可以正常工作。当我在服务器端构建项目时出现问题,每个页面“刷新”“F5”登录页面显示大约 1 秒,然后重定向到我所在的页面。网址始终保持不变。

如何解决此故障?

其他问题的示例,没有任何答案: Angular 2+ guard 在页面刷新时有奇怪的行为(我使用 express 用于 ssr 而不是 .net)

  public isAuthenticated(): boolean {
    if (typeof window !== 'undefined') {
      const token = localStorage.getItem(this.AUTH_TOKEN);
      if (!token) {
        return false;
      }
      return !this.tokenExpired(token);
    }
  }

标签: angularexpressserver-side-rendering

解决方案


在 SSR 构建期间,用户没有登录,并且 !token 条件被认为是真实的,它呈现登录路由

解决方案:通过isPlatformBrowser()和isPlatformServer()检测当前运行时是浏览器还是服务器

constructor(public auth: AuthService, public router: Router,
  @Inject(PLATFORM_ID) private platformId: Object,) { }

  canActivateChild(): Observable < boolean > {

    if(isPlatformBrowser(this.platformId)) {

      if (!token) {return false;}  }

    if (isPlatformServer(this.platformId)) {}

    return of(true);
  }

推荐阅读