![](/img/trans.png)
[英]Returning an Observable<boolean> from canActivate and redirect on false
[英]Returning an Observable<boolean> from canActivate method and redirect on false
我一直在尋找沒有運氣的解決方案。 如果用戶獲得授權,我需要調用服務器,並且我需要 canActivate 方法來等待該調用的結果。 但我似乎無法將碎片拼湊在一起。 下面是我的代碼,我的問題在代碼的注釋中。
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.
});
}
認證服務
isAuthorized(user:EUser){
return this.http.post(ConnectionHelper.SERVER_URL+
ConnectionHelper.USER+ConnectionHelper.ISAUTHORIZED,user).map(res => res.json());
}
您的方法是正確的,您只需要將服務器響應映射到bool
值。 例如:
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']);
}
});
}
您可以再次使用 promise 和 return value 以在 canActivate 中使用。 如果假設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;
});
}
請注意, then
鏈再次返回Promise
並在 next then
調用中可以訪問return isValidUser
。
我使用這種模式,它對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.