我需要实现 CanActivateFn 防护来阻止 Angular 项目中未经身份验证的用户。
到目前为止,我尝试了不同的方法并塑造了这个守卫。
import { inject } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivateFn,
Router,
RouterStateSnapshot,
UrlTree,
} from '@angular/router';
import { IUser } from '../model/user.model';
export const authGuard: CanActivateFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean | UrlTree> | boolean | UrlTree => {
let isAuthenticated = false;
let baseUrl: string = 'https://localhost:44411/';
let currentUser = <IUser>{};
// I need to get user info syncronusly
fetch(baseUrl + 'Account/GetUser')
.then((response) => response.json())
.then((json) => {
currentUser = jsonas IUser;
})
.catch((error) => {
console.error('There was an error to get user information.');
});
isAuthenticated = currentUser.isAuthenticated;
// 👇 Redirects to login route
const isAnonymous = !isAuthenticated;
if (isAnonymous) {
return inject(Router).createUrlTree(['/', 'login']);
}
return isAuthenticated;
};
问题是我需要找到一种同步获取用户数据的方法,以便能够根据用户数据进行验证。
请建议如何实现要求或建议不同的方法。 注意:我需要使用 fetch 来获取用户数据。
提前感谢您的帮助。
将 Promise 转换为可观察的,然后使用
map
验证错误,然后导航。catchError