import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' }) export class AuthService {
constructor(private http: HttpClient) { }
// other auth-related methods
// method to check if user has an admin role
isAdmin(): Observable {
// make a GET request to the backend API to get the user's role
return this.http.get('/api/user/role').pipe(
map(role => {
if (role === 'admin') {
return true;
} else {
return false;
}
})
);
}
}
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service';
@Component({ selector: 'app-admin-component', templateUrl: './admin.component.html', styleUrls: ['./admin.component.css'] }) export class AdminComponent implements OnInit {
constructor(private authService: AuthService) { }
ngOnInit() {}
// method to perform admin-only actions
doAdminAction() {
this.authService.isAdmin().subscribe(isAdmin => {
if (isAdmin) {
// perform admin-only action here
} else {
// display error message to user
}
});
}
}