不确定如何将值从Observable返回到CanActivate
导航继续。
我有一个CanActivate实现,它向我的服务器发出http请求
它将结果放在主题
中
取决于某些条件(如果)
它可以被拿起并返回CanActivate
继续导航
但是当事情发生的时候, 我似乎无法弄清楚如何到达 来自该订阅的布尔值。
myVar = pullProp;
authService#isAdmin()是:
private isAdminSubj: Subject<boolean> = new Subject<boolean>();
private isAdmin: Observable<boolean> = this.isAdminSubj.asObservable();
private go:boolean = false;
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean{
/* to store and redirect after login if user not logged in */
let target_url: string = state.url;
this.verifyLoginForAdmin( target_url );
this.isAdminSubj.subscribe(user_authorized => { this.go = user_authorized;} );
return this.go;
}
verifyLoginForAdmin( target_url: string ){
if( this.authService.isLoggedin() ){
let token_email =
this.authService
.jwt_helper
.decodeToken( localStorage.getItem( this.authService.jwt_name ) ).email;
this.authService.isAdmin( token_email )
.subscribe({
next: data => {
if( data )
this.isAdminSubj.next(true)
else{
this.router.navigate( [ '/coding-blog' ]);
this.isAdminSubj.next(false);
}
},
error: error => console.log("CanActivate Error-->", error),
complete: () => console.log("complete")
})
}else
this.authService.targetUrl = target_url;
this.router.navigate( [ '/projects' ] );
this.isAdminSubj.next(false);
}
}
我也试过了isAdmin( email: string ): Observable<boolean>{
return this.getDbInfo
.getOneUserByEmail( email )
.map( res => res.json().data.admin );
}
,但在哪里订阅并获取值:
CanActivate():Observable<boolean>
答案 0 :(得分:1)
您不必立即从boolean
返回canActivate
,您也可以返回Observable
或Promise
。
https://angular.io/docs/ts/latest/api/router/index/CanActivate-interface.html
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean>|Promise<boolean>|boolean
}
如果您立即知道答案,请返回boolean
,如果您需要致电服务/ Observable<boolean>
以确定答案,请返回Http
。
答案 1 :(得分:0)
有效表格是:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>{
let target_url: string = state.url;
return this.verifyLoginForAdmin( target_url );
}
this.vefityLoginForAdmin( target_url );
逻辑已经实现后必须返回一个observable。
感谢名单!