簡體   English   中英

Angular canActivate Guard with API

[英]Angular canActivate Guard with API

我目前正在開發一個 Angular 網頁,在后端使用 python API。 我想添加一個 canActivate Guard,以確保用戶位於 Adminlist 中,位於另一台服務器上。

我的問題是,警衛似乎不等待 API 的響應,我在警衛本身中使用 window.alert 對其進行了測試,它向我顯示了“未定義”作為輸出。 當我在我的 auth.service 中測試我的方法時,我在我的 console.log 中得到了正確的響應,所以我的方法似乎返回了正確的布爾值,但我的守衛似乎沒有等待 API 的答案。

我得到以下代碼:

auth.service.ts:

import { HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

import { IAuth } from './IAuth';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

   constructor(private http: HttpClient) { }

Acc: boolean;
getauth(): Observable<IAuth['Access']> {
return this.http.get<IAuth['Access']>('http://x.x.x.x:5555/auth');
}

get Access(): boolean {
   this.getauth().subscribe( data =>
   this.Acc = data);
return this.Acc;
}

}

這是我的 auth.guard.ts:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

import { AuthService} from './auth.service';

@Injectable({
  providedIn: 'root'

})
export class AuthGuard implements CanActivate {
   constructor (
      private auth: AuthService,
      private router: Router
  ) {}
    canActivate(
       next: ActivatedRouteSnapshot,
       state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
          if (!this.auth.Access) {
             this.router.navigate(['/noaccess']);
             window.alert(this.auth.Access);
             window.alert(this.auth.Acc);
           }
          return true;
  }
}

我希望你們能幫我解決這個問題,就像我說的,我在警衛(未定義)中得到錯誤的響應,訪問屬性和訪問方法。

get Access(): boolean {
   this.getauth().subscribe( data => this.Acc = data);
   return this.Acc;
}

您不會等待 HTTP 調用完成,因此您的守衛也不會等待。 改用這個。

get Access(): Observable<any> {
   return this.getauth().pipe(tap(data => this.Acc = data));
}

你守衛然后變成

canActivate(
  next: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth.Access.pipe(map(res => {
      if (!res) { this.router.navigate(['/noaccess']); }
      return !!res;
    }));
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM