angular - Angular canActivate 从服务中获取更新的变量
问题描述
我有一个来自服务的发布请求,如果用户登录则返回,我想设置一个 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();
}
推荐阅读
- docker - Docker :: 如何查看由 Docker for Mac 制作的图像中的包装?
- path - 网络共享脚本 - 自动检查驱动器号和路径
- c# - 需要转换代码以选择随机行并显示
- axios - 如果 axios 请求失败,error.response 未定义
- excel - 根据单元格值从一个工作表复制行并粘贴到另一个工作表到下一个可用行
- c# - 捕获 svclog 文件的第二个 E2ETraceEvent
- java - JNI:产生需要与 Java 交互的线程的本地方法
- python - org.apache.spark.api.python.PythonRDD.saveAsNewAPIHadoop文件错误
- javascript - 异步等待'承诺{
} 与 Array.prototype.map - julia - 在 Julia 1.0.2 中查找函数