angular - 在 canAcitvate 中调用 api - Angular
问题描述
我正在尝试与 Auth 守卫一起工作。我有一个 httpcall,它根据来自 HTTP 调用的响应设置真/假值。问题是:1)httpClients 返回一个 observable 2)httpClient 订阅需要在 Authorized 方法被调用之前发生,这样 hasSessionFlag 已经设置。
双重服务.TS
hasSession() {
return this.http.get<{}>('API CALL', {
withCredentials: true,
observe: 'response'
}).subscribe((res=>{
if(res.status === 200) {
this.hasSessionFlag = true;
} else {
this.hasSessionFlag = false
}
}));
}
//Check if all the logical conditions of the user sessions pass*
isAuthorized(): boolean {
if (this.hasSessionFlag) {
this.authService.login();
} else {
this.dualLoginRedirect();
}
}
canActivate(): boolean {
return this.isAuthorized();
}
路由器.TS
{
canActivate: [DualLogonService],
path: 'test',
component: TestPageComponent
}
解决方案
您可以轻按一下并设置 hasSessionFlag 的值,而不是订阅您的 http 调用......所以这样做..
hasSession() {
return this.http.get<{}>('API CALL', {
withCredentials: true,
observe: 'response'
}).pipe(
tap(res=>{
if(res.status === 200) {
this.hasSessionFlag = true;
} else {
this.hasSessionFlag = false
}
}))
.switchMap(res=>{
if(this.hasSessionFlag)return this.authService.login();
else return this.dualLoginRedirect();
}));
}
isAuthorized(): boolean {
if (this.hasSessionFlag) {
this.authService.login();
} else {
this.dualLoginRedirect();
}
}
假设您的 authService.login() 和 dualLoginRedirect() 是可观察的
推荐阅读
- javascript - JavaScript 降序日期排序列表
- javascript - 在redux中更新数组时如何避免改变状态
- firebase - 用于存储触发函数的 Firebase 函数。storage.object().onFinalize() 退出而不等待异步调用
- applescript - 不允许 AppleScript 应用程序发送击键
- python - 小部件父级在 KV 文件中不立即可用
- python - Luigi LocalTarget 返回通用文件名写入 nc 文件
- arrays - Bash:获取“ls”命令结果的数组中的元素数?${#a[@]} 不起作用
- java - 在 Java 中将 Markdown 文件解析为 JSON 对象
- dbeaver - 如何在 DBeaver 中查找执行时间而不是执行 + 获取
- list - 计算列表中忽略相邻重复项的元素数