我有以下问题: Observable总是返回undefined。我想我真的不知道如何使用HttpClient来与AuthGuard一起工作。
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable < boolean > {
var bool
var token = localStorage.getItem('Authorization');
if (token != null) {
this.http.post('http://localhost:5000/v1/logstatus?token=' + token, this.authData).subscribe(res => {
if (!JSON.stringify(res).includes('AuthorizationNotFound')) {
bool = true
} else {
bool = false
}
})
} else {
bool = false
}
console.log(bool)
return observableOf(bool)
}
发布于 2019-02-26 21:54:09
this.http.post是一个异步操作,因此在结果定义bool之前返回of(bool)。换句话说,甚至在POST结束之前就解析了of(bool),并设置了bool的值。
相反,您可以将响应可观察值map为布尔值,并直接返回它。将您的if块更改为:
if (token != null) {
return this.http.post('http://localhost:5000/v1/logstatus?token=' + token, this.authData)
.map(res => !JSON.stringify(res).includes('AuthorizationNotFound'));
}这将使POST可观察到直接映射到您正在寻找的布尔值。
不相关,但如果您还没有这样做,您应该考虑向此调用添加错误处理逻辑,因为如果POST调用失败,您的保护将失效。
https://stackoverflow.com/questions/54886873
复制相似问题