下面是我的代码,我想做的是试图将返回值直接放入 canActivate 返回,但问题是它会在运行“this._authService.isAdmin(token)”方法之前先运行检查。我知道它是因为异步。但是如何防止呢?我已经有想法了。提前致谢。
我已经尝试将该方法放在构造函数上,但结果仍然相同。
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthenticationService } from "../_services/authentication.service";
@Injectable()
export class AdminGuard implements CanActivate {
isAdmin: boolean = false;
constructor(
private _authService: AuthenticationService,
private router: Router) {
}
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
var token = this._authService.getJwtToken();
this._authService.isAdmin(token).subscribe(
res => {
//res will return true or false value
this.isAdmin = res;
}
);
if(this.isAdmin){
return true;
}
this.router.navigate(['/']);
return false;
}
}