[英]Returning an Observable<boolean> from canActivate method and redirect on false
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.
如果用户获得授权,我需要调用服务器,并且我需要 canActivate 方法来等待该调用的结果。 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认证服务
isAuthorized(user:EUser){
return this.http.post(ConnectionHelper.SERVER_URL+
ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user).map(res => res.json());
}
Your approach is correct, you just need to map the server response to a bool
value.您的方法是正确的,您只需要将服务器响应映射到
bool
值。 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']);
}
});
}
you can use promise and return value again for using in canActivate.您可以再次使用 promise 和 return value 以在 canActivate 中使用。 if assume
isAuthorized
return boolean
value you can use this code:如果假设
isAuthorized
返回boolean
值,您可以使用以下代码:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
let user: EUser = new EUser();
user.sessionId = localStorage.getItem("sessionId");
return this.authenticationService.isAuthorized(user)
.toPromise()
.then((isValidUser) => {
if (!isValidUser) {
this.router.navigate['login'];
}
return isValidUser;
});
} }
note that then
chain return Promise
again and return isValidUser
is accessible in next then
call.请注意,
then
链再次返回Promise
并在 next then
调用中可以访问return isValidUser
。
i use this pattern and it worked for me.我使用这种模式,它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.