[英]Angular how do I use await with .subscribe
I am currently building a route guard that checks if my client is authenticated.我目前正在构建一个路由守卫来检查我的客户是否经过身份验证。 Since I am using http only cookies I have to send a request to my server which then returns if the cookie is valid or not.因为我只使用 http cookie,所以我必须向我的服务器发送一个请求,如果 cookie 有效或无效,则该请求会返回。 This is the code for my guard:这是我的守卫的代码:
export class AuthGuard implements CanActivate {
constructor (private auth: AuthService){}
async canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Promise<boolean> {
let isAuthenticated : boolean = false;
await this.auth.getAuthStatus().subscribe(
res => {
if(res.status == 200){
isAuthenticated = true;
}
})
console.log(isAuthenticated)
return isAuthenticated;
}
}
and the service is just a simple http call:该服务只是一个简单的 http 调用:
getAuthStatus(): Observable<HttpResponse<any>>{
return this.http.post(environment.server + environment.routes.authRoutes.status, "", {
withCredentials: true,
observe: 'response'
})
}
The problem I am facing is that my guard has to return a boolean for the router, and since I am using .subscribe it returns false since it returns siAuthenticated before I .subscribe finishes.我面临的问题是我的守卫必须为路由器返回一个布尔值,并且由于我使用 .subscribe 它返回 false 因为它在我 .subscribe 完成之前返回 siAuthenticated 。 I tried adding await and returning a promise, but either it does not work in my case or I did not use it correctly.我尝试添加 await 并返回一个承诺,但在我的情况下它不起作用或者我没有正确使用它。 I tried finding a solution in different posts, but none of them worked for me (Or I just didnt understand them properly and implemented them in the wrong way).我尝试在不同的帖子中找到解决方案,但没有一个对我有用(或者我只是没有正确理解它们并以错误的方式实现它们)。
Thank you谢谢
await
needs a Promise
So you can use toPromise()
method of Observable
and change the return type of getAuthStatus()
. await
需要一个Promise
所以你可以使用Observable
toPromise()
方法并改变getAuthStatus()
的返回类型。
But as @ShamPooSham mentioned in the comment, I also recommend returning Observable
instead of a Promise
from the guard.但正如评论中提到的@ShamPooSham,我还建议从守卫返回Observable
而不是Promise
。
getAuthStatus(): Promise<HttpResponse<any>>{
return this.http.post(environment.server + environment.routes.authRoutes.status, "", {
withCredentials: true,
observe: 'response'
}).toPromise()
}
await this.auth.getAuthStatus().then(res => {...})
for newer RxJS version you can write对于较新的 RxJS 版本,您可以编写
const response = await lastValueFrom(this.auth.getAuthStatus());
and for older而对于年长的
const response = await this.auth.getAuthStatus().toPromise();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.