[英]call api in canAcitvate - Angular
我正在尝试与Auth Guard进行交流。 我有一个httpcall,它根据来自HTTP调用的响应设置一个true / false值。 问题是:1)httpClients返回一个可观察的对象2)必须在调用Authorized方法之前发生httpClient订阅,这样就已经设置了hasSessionFlag。
双重服务
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();
}
路由器
{
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()是可观察到的
根据您的最新代码,我想这就是您想要做的:
如果API返回的状态为200,则您要调用“ this.authService.login();
”否则调用“ this.dualLoginRedirect();
”
[根据编写此答案时的代码-您的isAuthorized()
方法不返回布尔值,而是返回未定义。 它必须返回布尔值或布尔值或promise的可观察值。 我假设状态为200时它将返回true
否则将返回false
]。 在这种假设下,您只能具有canActive()
方法:
canActive(): Observable<boolean> {
return this.http.get<{}>('API CALL', {
withCredentials: true,
observe: 'response'
})
.pipe(
map(res => {
if(res.status === 200) {
//OR DO here whaterevr you want to do
this.authService.login();
//return true will render the associated component
//i.e. pass the guard
return true;
} else {
this.dualLoginRedirect();
//return false will fail the guard.
return false;
}
})
);
}
您的保护服务将自动订阅 canActivate()
方法返回的observable。
另外,请注意,在这种方法中,没有声明任何类成员。 虽然如果您的警卫需要它,只需声明它们并根据您的要求使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.