我相信您想要做的是在路由加载前验证用户的身份验证。这样,您始终可以确保用户的 id 可供使用。一种方法是使用Route Guard。这将确保用户身份验证预路由加载。
在此示例中,我将用户数据存储在本地存储中,以便当用户刷新页面或意外点击时,他们的身份验证基于存储中用户对象与内存中用户对象的令牌到期时间。
如果用户通过验证,您可以安全地调用用户的内存值而无需订阅。
auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { StorageService } from '../services/storage.service';
import { UserService } from '../services/user.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private userService: UserService,
private storageService: StorageService
) { }
canActivate(
): Promise<boolean> | boolean {
return new Promise((resolve) => {
const userStore = this.userService.user$.value
if (!userStore.id) {
const userStorage = this.storageService.get('user')
if (!userStorage) {
this.router.navigate(['login'])
resolve(true)
} else {
this.userService.user$.next(userStorage)
resolve(true)
}
} else {
resolve(true)
}
})
}
}
main.routes.ts
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
}
dashboard.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.style.scss'],
})
export class DashboardComponent {
constructor(private userService: UserService) {
const user = this.userService.user$.value
console.log('user should be active and validated here', user)
}
}