带订阅的Angular Auth Guard [英] Angular Auth Guard with Subscribe

查看:77
本文介绍了带订阅的Angular Auth Guard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个身份验证卫士,需要运行api调用以查看他们是否具有访问权限.我不认为有可能从订阅返回数据,但是我还能怎么做呢?

I have an auth guard and need to run an api call to see if they have access. I don't believe it's possible to return data from a subscribe but how else would I do this?

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

I need to get the userid and then call the api and then return either true of false depending on the api call.

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

推荐答案

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

You need to return Observable<boolean> that will resolve to true/false depending on authentication request.

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

这篇关于带订阅的Angular Auth Guard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆