[英]Angular4 issue with http requests
在我的Angular 4应用程序中,我正在开发一项誓言保护服务。 我想在那里检查令牌是否处于活动状态,如果不是,则用户需要再次登录。
以下是我用来实现所需功能的函数:
isLogedIn(){
return this.http.get(this.baseUrl+"/check-token?token="+this.currentUser.token).map(res => res.json())
.subscribe(response => {
let logedinUser = JSON.parse(localStorage.getItem('currentUser'));
if(response.message == "_successful" && localStorage.getItem("currentUser") != null){
return true;
}else{
return false;
}
},err =>{
console.log(err);
return false;
});
}
但问题是在auth gurd函数中,我无法获得此函数的确切输出值。 波纹管是我的身份验证功能:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(this.userService.isLogedIn());
if (this.userService.isLogedIn()) {
return true;
} else {
this.router.navigate(['/login'], {
queryParams: {
return: state.url // curent url as a parameter to the login page
}
});
return false;
}
}
当我使用console.log(this.userService.isLogedIn());
它打印订户对象而不是返回值。 如何从isLogedIn()函数返回值?
因为您确实要返回订阅。 `
this.http.get(...)
是一个Observable
; this.http.get(...).map(...)
是一个Observable
; this.http.get(...).map(...).subscribe(...)
是一个Subscription
; 该subscribe
方法返回一个Subscription
,而不是return something
这是内部subscribe
程序。
我建议您采取什么措施:在守卫中返回可观察的自身( canActivate
接受Observable<boolean>
作为返回)。 不要在isLogedIn()
调用subscribe
:
isLogedIn(): Observable<boolean>{
return this.http.get(this.baseUrl+"/check-token?token="+this.currentUser.token).map(res => res.json())
.map(response => {
let logedinUser = JSON.parse(localStorage.getItem('currentUser'));
if(response.message == "_successful" && localStorage.getItem("currentUser") != null){
return true;
}else{
return false;
}
});
}
请注意,我两次调用map
:最后一个是操纵您的响应以返回布尔值。 最后,在canActivate
:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.userService.isLogedIn().do(response => {
if (!response) {
this.router.navigate(['/login'], {
queryParams: {
return: state.url // curent url as a parameter to the login page
}
});
}
})
}
我插入运算符do
,它是一个独立的回调,用于管理路由。
你的功能应该像
isLogedIn(): Observable<boolean> {
return this.http.get(this.baseUrl + '/check-token?token=' + this.currentUser.token)
.map((res: Response) => {
const response = res.json();
return response.message == "_successful" && localStorage.getItem("currentUser") != null;
}).catch((error: Response) => {
return false;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.