Angular2-返回带有canActivate的布尔值 [英] Angular2 - return boolean with subscribe to canActivate
本文介绍了Angular2-返回带有canActivate的布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Angular的新手,我需要实现一个返回true/false的函数,我将在canActivate Guard中使用return,但是此函数使用了http.get的api,因此就像该函数的通信是异步的始终返回FALSE,因为http.get尚在处理中.
I am new in Angular, I need to implement a function that returns true/false, I going to use the return in canActivate guard, but this function consumes a api by http.get, so like the communication is asynchronous this function always return FALSE, because http.get yet is in process.
我的班长:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
if (this.loginService.isLoggedIn()) {
return true;
}
this.loginService.redirectUrl = url;
this.router.navigate(['login']);
return false;
}
和函数isLoggedIn()
and function isLoggedIn()
isLoggedIn() {
let logged: boolean = false;
this.http.get('api/values', this.httpService.headers())
.map((res: Response) => {
logged = res.json();
});
return logged;
}
我读了很多问题,但找不到答案.
I read many questions, but I don't found the answer.
推荐答案
警卫类型表示它可以返回
guard typings says it can return
Observable<boolean>, Promise<boolean> or boolean
因此将isLoggedIn更改为:
so change isLoggedIn to:
isLoggedIn() {
return this.http.get('api/values', this.httpService.headers())
.take(1)
.map((res: Response) => res.json());
}
更新
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.isLoggedIn().map(loggedIn => {
if(!loggedIn) {
this.loginService.redirectUrl = url;
this.router.navigate(['login']);
}
return loggedIn;
}
}
这篇关于Angular2-返回带有canActivate的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文