问题描述
我想通过检查用户是否从服务器登录但不执行异步功能来保护路由
I would like to protect my routes by checking if a user is logged in from the server but the asynchronous functions don't get executed
这是我的代码:
canActivate (route: ActivatedRouteSnapshot , state: RouterStateSnapshot): Observable<any> {
let permission = route.data[ "permission" ]; //permissions are set on the routes
if(permission){
..execute another function which works
)
}else{
return this.checkLogin() //this one is the one that fails
}
}
在功能 checkLogin
上:
checkLogin (url?: string): any {
this.authService.checkLoggedin()
.subscribe(
res=>{
if(res){
return true;
}else{
this.router.navigate ( [ '/login' ] );
return false
}
}
)
}
现在使用身份验证服务
checkLoggedin():Observable<any> {
//check from server if user is loggdin
return this._httpclient.get(this.authurl + "/default/is-loggedin")
.map(res => {
return res.json().data;
},error=>{
return Observable.of(false);
}
);
}
我哪里出问题了?
推荐答案
checkLogin
必须返回 Observable< boolean>
或 Promise< boolean>
(如果是同步的,则为普通的 boolean
).你什么也没退.
checkLogin
must return either an Observable<boolean>
or a Promise<boolean>
(or a plain boolean
if it were synchronous). You aren't returning anything.
尝试一下.只需使用 map
来修改 checkLoggedin()
发出的值,然后返回 Observable
,而不是 subscribe
.适当的布尔值.
Try this. Instead of subscribe
just use map
to modify the value emitted by checkLoggedin()
and then return the Observable
with the appropriate boolean.
checkLogin (url?: string): Observable<boolean> {
return this.authService.checkLoggedin()
.map(
res=>{
if(res){
return true;
}else{
this.router.navigate ( [ '/login' ] );
return false
}
});
}
一个好的提示可能是永远不要将函数声明为返回 any
,始终将其声明为您要返回的实际类型,然后编译器可以执行其工作并告诉您是否忘记了在实际需要返回结果时返回结果.
A good tip might also be to never declare a function as returning any
, always declare it as the actual type you are returning and then the compiler can do its job and tell you if you forgot to return a result when you actually needed to return one.
类似地, checkLoggedin():Observable< any>
应该是 checkLoggedin():Observable< boolean>
,以最大程度地捕获错误(并且您可能必须这样做)对json数据进行一些转换,然后使其生效).
Likewise checkLoggedin():Observable<any>
should be checkLoggedin():Observable<boolean>
to maximise the chance of catching errors (and you may have to do some conversion on the json data then to make it work).
这篇关于执行异步功能的Angular2 Authguards失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!