在 angular 4 个守卫中使用一项服务

Using a service in angular 4 guards

请协助 angular 守卫,我有以下 angular 守卫如下:

export class RoleGuard implements CanActivate {

 private role: any;
 constructor(private router: Router, private accountService: AccountService) 
 {}

   canActivate(
      next: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
   ): Observable<boolean> | Promise<boolean> | boolean {

     this.accountService.getUserRole().subscribe(res => this.role = res);
     if (this.role === 'admin') {
         return true;
     }
   return false;
 }
}

在服务中:

  getUserRole(): Observable<Response> {
  const options = this.headers();
    return this.http.get(`${environment.ApiUrl}/Roles/getRole`,options)
  .map(res => res.json())
  .catch(res => Observable.throw(res.json()));
 }

我正在尝试订阅 getUserRole() 函数,然后将响应分配给 this.role 但那没有发生,角色始终是 undefined。当我执行 ...subscribe(res => console.log(res)) 时,我看到了响应数据。

您必须等待异步 HTTP 请求的结果,然后才能检查是否可以激活该路由。

尝试返回一个新的 Observable:

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {

    return new Observable(observer => {   
        //
        this.accountService.getUserRole().subscribe(role => {
            //
            if (role === 'admin') {
                observer.next(true); // Allowing route activation
            } else {
                observer.next(false); // Denying route activation                
            }
        }, err => observer.next(false)); 
    }); 
}