Angular - AuthGuard & Auth Service - Beobachtbar immer zurückgeben
Posted: 01 Mar 2025, 13:51
Ich versuche meine Routen zu schützen, die meine Authuards verwenden. Der AuthGuard ruft den AuthService auf, auf den zugegriffen wird, und die API, um zu überprüfen, ob der Benutzer zu einer bestimmten Anzeigengruppe gehört.
Ich habe versucht, die Obseravle -Methode zu entfernen, um den booleschen Wert zurückzugeben, aber damit AuthService funktioniert, müssen Sie ihn beobachtbar sein. />
Code: Select all
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate } from '@angular/router';
import { Injectable, inject } from '@angular/core';
import { AuthService } from '../shared/auth.service';
export class AuthorisedUserGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router, private route: ActivatedRouteSnapshot) { }
async canActivate() {
let result = await this.authService.isAuthorisedUser(this.route.data['role']).toPromise();
if (!result) {
this.router.navigate(['/unauthorised'])
}
return true;
}
}
AuthService:
export class AuthService {
constructor(private router: Router, private http: HttpClient) {
}
URL_Config: Configuration = new Configuration();
public accessGranted: boolean = false;
public route: string = "";
isAuthorisedUser(role: string): Observable {
this.route = role;
let apiURL = `${this.URL_Config.URL}/api/UserAccess/checkUserAccess?route=${this.route}`;
return this.http.get(apiURL, { withCredentials: true });
}
}