Angular用户及配置持久化问题:路由守卫报错与数据异常
问题1:路由守卫调用CookieService时提示document不可用
路由守卫执行时触发document未定义错误,虽当前功能暂时正常,但存在潜在风险——路由守卫可能在DOM未初始化的阶段(如SSR启动)执行,此时全局document对象尚未存在。
解决方案
修改CookieService,通过Angular官方提供的DOCUMENT注入令牌安全获取document对象,避免直接访问全局变量:
import { Injectable, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class CookieService { constructor(@Inject(DOCUMENT) private document: Document) { } /** * Gets an object like cookie * @param name name of the cookie to get * @returns the value of the cookie requested or undefined */ public getCookie(name:string):object|undefined{ const cookies = this.document.cookie.split("; ") for (const cookie of cookies){ const [key,value] = cookie.split("=") if (key === name){ try{ let values = JSON.parse(decodeURIComponent(value)); console.log("Values", values) return values; }catch(error){ console.error('Error parsing cookie value:', error); return undefined; } } } console.log(`Cookie with name "${name}" not found.`); return undefined; } }
若项目启用SSR,可在FirebaseService中添加浏览器环境判断,避免非浏览器环境执行Cookie操作:
import { Injectable, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class FirebaseService { // ... 原有代码 constructor( private cookie_service:CookieService, @Inject(PLATFORM_ID) private platformId: Object ) { // ... 原有初始化代码 } private checkPersistance():void{ if (isPlatformBrowser(this.platformId)) { const credentials = this.cookie_service.getCookie("userCredentials") if(credentials){ this.userCredential=credentials as UserCredential; }else{ console.log("No user persisted") } } } }
问题2:读取Cookie时数据变为Promise对象
登录组件调用ProfileService.getUserProfile()后存入Cookie,但在OportunidadesComponent读取时,数据变成Promise对象无法使用——原因是getUserProfile()是异步函数,返回Promise,但代码未用await获取实际数据就直接存入了Cookie。
解决方案
修改LoginComponent的onSubmit方法,对异步调用添加await,获取实际用户数据后再存入Cookie:
async onSubmit(){ let username = this.loginForm.get("username")!.value as string; let password = this.loginForm.get("password")!.value as string; try{ await this.auth.Login(username,password); this.ToasterTools.setKind(ToastKind.success); this.ToasterTools.setTitle("Inicio de Session exitoso"); this.ToasterTools.setMessage(""); this.ToasterTools.showToast(); // 添加await获取实际用户数据 const user_profile = await this.profile.getUserProfile(); if(user_profile!=null){ await this.cookie_service.setCookie("user_profile", user_profile,undefined ,1); }else{ this.ToasterTools.setKind(ToastKind.error); this.ToasterTools.setTitle("Error"); this.ToasterTools.setMessage("La carga de tu perfil fallo, intentelo denuevo mas tarde"); this.ToasterTools.showToast(); return; } this.router.navigate(["/Oportunidades"]); }catch(error){ this.ToasterTools.setKind(ToastKind.error); this.ToasterTools.setTitle("Error"); this.ToasterTools.setMessage("Usuario o contraseña incorrectos"); this.ToasterTools.showToast(); console.error(error); } }
报错与异常截图
问题1报错截图

问题2数据异常截图

内容的提问来源于stack exchange,提问作者App Scripter
相关产品推荐
相关产品推荐

