本文介绍了返回Observable< boolean>从canActivate方法并在false上重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在寻找没有运气的解决方案.如果用户被授权,我需要调用服务器,并且我需要canActivate方法来等待该调用的结果.但是我似乎无法拼凑而成.下面是我的代码,我的问题在代码的注释中.
I have been searching for a solution with no luck. I need to call the server if a user is authorized and i need canActivate method to wait for the result for that call. But i can`t seem to put pieces together. Below is my code, my question is in the comments of the code.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
let user: EUser = new EUser();
user.sessionId = localStorage.getItem("sessionId");
//I am not sure how to implement this part.
// I need to recieve the response and get user.isAuthorized value and return it
// as an observable.
this.authenticationService.isAuthorized(user).subscribe((user)=>{
//Here i need to get user.isAuthorized and
//if the value is false, i need to navigate to login with this.router.navigate['login'] and return it.
//if the values it true, i need the code continue as it is.
});
}
AuthenticationService
AuthenticationService
isAuthorized(user:EUser){
return this.http.post(ConnectionHelper.SERVER_URL+
ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user).map(res => res.json());
}
推荐答案
您的方法是正确的,您只需要将服务器响应映射到bool
值即可.例如:
Your approach is correct, you just need to map the server response to a bool
value. For example:
export interface AuthState {
username:string;
sessionId:string;
isAuthorized:boolean;
}
isAuthorized(user:EUser): Observable<AuthState> {
return this.http.post(ConnectionHelper.SERVER_URL+
ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user)
.map(res => res.json());
}
// Inject Router instance in the constructor of the guard class
// import required rxjs operators
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
let user: EUser = new EUser();
user.sessionId = localStorage.getItem("sessionId");
return this.authenticationService.isAuthorized(user)
.map(user => user.isAuthorized)
.do(auth => {
if(!auth){
this.router.navigate(['/login']);
}
});
}
这篇关于返回Observable< boolean>从canActivate方法并在false上重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!