[英]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.