【发布时间】:2020-06-12 14:35:23
【问题描述】:
我对 Angular 还很陌生,在这里我很感激一些指导。我在 AuthService 中的 userLoggedIn 函数总是返回 false,因为这个函数返回变量 userIsLoggedIn 的值,该变量最初被赋值为 false 并且它永远不会到达代码块 - 在执行 return 语句之前传递给 subscribe 方法的回调函数中的this.userIsLoggedIn=res.tokenValid;。我相信这是由于 javascript 处理函数的异步性,但是如何在完全执行我的回调函数之前阻止执行到达 return 语句,以便我的函数可以返回 true 如果我的响应对象的 validToken 属性包含 true 值?
我尝试了以下方法但没有帮助:
-
在我的回调函数上使用了 async-await -
this.httpReq.verifyToken(token) .subscribe(**async** res =>{ this.userIsLoggedIn= **await** res.tokenValid; })``` -
制作了整个 userLoggedIn 函数async-await
**async** userLoggedIn():boolean{ **await** this.httpReq.verifyToken(token) }
//Auth Service
export class AuthService {
userIsLoggedIn=false;
constructor(private router:Router, private repo:ProductRepository,
private httpReq:HttpRequestService) {}
userLoggedIn():boolean{
const token=this.getLocalToken();
if(!token){
return false;
}
this.httpReq.verifyToken(token)
.subscribe(async res =>{
this.userIsLoggedIn=await res.tokenValid;
})
return this.userIsLoggedIn;
}
}
//verifyToken method in my HttpRequestService
export class HttpRequestService {
constructor(private http: HttpClient) { }
verifyToken(token:string){
const headers=new HttpHeaders({
'Content-Type':'application/json',
'Authorization':token
})
return this.http.post<{message:string, tokenValid:boolean}>('http://localhost:3000/users/authenticate', null, {headers:headers})
}
}
【问题讨论】:
标签: angular async-await subscribe