0

下面是我的代码,我想做的是试图将返回值直接放入 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;

  }
}
4

1 回答 1

0

您可以为此使用可管道运算符

canActivate(): Observable<boolean> {
  let token = this._authService.getJwtToken();
  return this._authService.isAdmin(token).pipe(
    tap(isAdmin => {
      if (isAdmin) {
        this.router.navigate(['/']);
      }
    })
  );
}

// Usage:
canActivate.subscribe(value => {
  // do something...
});

请注意,点击运算符只是执行“副作用任务”。运算符返回的 observable 与tap之前的 observable 相同。现在,if isAdmin只有在 isAdmin observable 发出事件时才会评估 tap 运算符中的检查。

于 2018-03-21T03:19:42.547 回答