【问题标题】:Angular Auth Guard with Subscribe带有订阅的 Angular Auth Guard
【发布时间】:2019-11-13 20:28:02
【问题描述】:

我有一个身份验证守卫,需要运行一个 api 调用来查看他们是否有访问权限。我不相信可以从订阅中返回数据,但我该怎么做呢?

我需要获取用户 ID,然后调用 api,然后根据 api 调用返回 true 或 false。

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;
  }
}

【问题讨论】:

  • 我建议您编辑问题并更具体地说明您要达到的目标以及遇到的困难。

标签: angular typescript ionic-framework observable ionic4


【解决方案1】:

您需要返回Observable&lt;boolean&gt;,它将根据身份验证请求解析为真/假。

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);
                    }
                }
            );
        });
    });
}

【讨论】:

    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 2017-10-18
    • 2021-09-03
    • 2022-11-04
    • 2018-08-08
    • 1970-01-01
    • 2017-07-16
    • 2022-10-25
    相关资源
    最近更新 更多