angular - 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);
}
}
解决方案
在 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);
}
推荐阅读
- cloud-foundry - 禁用 Cloud Foundry RTR 日志
- regex - 删除文件中与模式不匹配的行
- excel - 隐藏多列 VBA Excel
- makefile - Makefile 目标作为两个列表的叉积
- java - 如何知道 Eclipse 插件项目中的透视图是否发生了变化?
- amazon-web-services - 延迟 AWS AppSync 突变
- c++ - 链接类静态变量而不包括整个类声明
- java - 在 AnyLogic 中建模人口密度
- angularjs - Angular JS 在满足条件时创建新的 div,否则添加到旧的
- javascript - jQuery 通过按下按钮更改 div 的内容( include() )