Angular 带订阅的 Auth Guard

Angular Auth Guard with Subscribe

我有一个 auth guard,需要 运行 一个 api 电话来查看他们是否有访问权限。我认为不可能 return 来自订阅的数据,但我还能怎么做?

我需要获取用户 ID,然后调用 api,然后 return 根据 api 调用是真还是假。

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class TeamcheckGuard implements CanActivate {
  success: boolean;

  constructor(
    private router: Router,
    private authService: AuthService
  ) {}

  // Checks to see if they are on a team for the current game they selected.
  canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
      this.authService.getUserId().then(() => {
        let params = {
          gameId: next.params.id,
          userId: this.authService.userId
       };

        this.authService.getApi('api/team_check', params).subscribe(
          data => {
            if (data !== 1) {
              console.log('fail');
              // They don't have a team, lets redirect
              this.router.navigateByUrl('/teamlanding/' + next.params.id);
              return false;
            }
          }
        );
      });
    return true;
  }
}

您需要 return Observable<boolean>,它将根据身份验证请求解析为 true/false。

canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return new Observable<boolean>(obs => {
        this.authService.getUserId().then(() => {
            let params = {
                gameId: next.params.id,
                userId: this.authService.userId
            };

            this.authService.getApi('api/team_check', params).subscribe(
                data => {
                    if (data !== 1) {
                        console.log('fail');
                        // They don't have a team, lets redirect
                        this.router.navigateByUrl('/teamlanding/' + next.params.id);
                        obs.next(false);
                    }
                    else {
                        obs.next(true);
                    }
                }
            );
        });
    });
}