【发布时间】:2021-02-01 16:50:40
【问题描述】:
我有一个带有两个 authGuard 服务的 Angular 应用程序:
export class AuthGuardService implements CanActivate {
constructor(public auth: AccountService, public router: Router) {}
canActivate(): Observable<boolean> {
return this.auth.identity().pipe(
map(account => {
if (account) {
return true;
}
this.router.navigate(['welcome']);
return false;
})
);
}
}
@Injectable()
export class StartupService implements CanActivate {
isAdmin: boolean;
constructor(public auth: AccountService, public router: Router, private sidebarService: SidebarService) {}
canActivate(): Observable<boolean> {
return this.auth.identity().pipe(
switchMap(account => {
this.isAdmin = account.isAdmin;
return this.sidebarService.getCompanies(account.id.toString());
}),
map(firms => {
if(this.isAdmin && Object.keys(firms).length === 0) {
this.router.navigate(['startup']);
return false;
}
return true;
}),
catchError(() => of(false))
);
}
}
在 AuthGuardService 中,我调用身份服务来检查我是否已登录,如果没有,我需要重定向到欢迎页面;在 StartupService 我调用相同的服务,我还检查我是否是管理员并且我有一些可用的数据(公司)。我还在 AppComponent 的 ngOnInit 中调用相同的服务,并使用 ngrx 将帐户状态保存在商店中。我调用相同的服务 3 次。避免这种情况的最佳方法是什么?我在哪里可以使用 ngrx 选择器?我在调试中看到 canActivate 在 ngOnInit AppComponent 之前被调用。有什么建议吗?
【问题讨论】:
标签: angular typescript