[英]Angular - Get Boolean Value from a Observable Service inside the CanActivate
[英]Angular canActivate get updated variable from service
我有一个来自服务的发布请求,该请求在用户登录时返回,我想将 authGuard 设置为仅在用户登录时显示管理面板。我的发布请求如下:
public isLoggedIn: boolean = false;
checkSesh(data: object) {
const options = {
headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
withCredentials: true
}
return this.http.post<any>(`${this.AUTH_SERVER}`, data, options).subscribe(
(res) => {
this.reload = res[0].reload;
if (this.reload === 0) {
this.isLoggedIn = true;
}
}
);
}
我的 authguard 有以下几点:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.service.isLoggedIn;
}
但它返回 false(它在订阅之前获取布尔值)。
在发布请求运行并且值已更新后,如何更新它?
谢谢
您需要在 canActivate 函数中返回 Observable 作为结果。 因此,您可以将结果映射到 checkSesh 函数中,以返回 true/false。 所以像这样:
checkSesh(data: object) {
const options = {
headers: new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'),
withCredentials: true
}
return this.http.post<any>(`${this.AUTH_SERVER}`, data, options)
.pipe(
map((res) => {
this.reload = res[0].reload;
if (this.reload === 0) {
this.isLoggedIn = true;
return true;
}
return false;
})
);
}
然后就在 canActivate 函数中,您可以执行以下操作:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.service.checkSesh();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.