There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict access to the /new page if a user has already created a CV, but this restriction should be lifted for admins or managers at all times :) Interestingly, my guard implementation fails to work when the user is both an admin and has a CV created; however, it performs well under other circumstances. I am utilizing rxjs version 6.6.3 for this task.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable, combineLatest } from 'rxjs';
import { map, finalize } from 'rxjs/operators';
import { PersonsService } from '../services/persons.service';
import { AdministrationService } from '../services/administration.service';
import { CustomSnackbarService } from '../services/custom-snackbar.service';
@Injectable({
providedIn: 'root',
})
export class CanCreateNewCv implements CanActivate {
constructor(
private usersService: PersonsService,
private router: Router,
private administrationService: AdministrationService,
private snackbarService: CustomSnackbarService
) {}
canActivate(): Observable<boolean> | boolean | Promise<boolean> {
let isAllowed = false;
const cv$ = this.usersService.getPersonsByPageAndFilter(10, 0).pipe(
map((data) => {
if (data.allDataCount > 0) {
this.router.navigateByUrl('/list');
return true;
}
return false;
})
);
const admin$ = this.administrationService.getCurrentUser().pipe(
map((currentUser) => {
if (currentUser.isAdmin || currentUser.isManager) {
return true;
}
return false;
})
);
return combineLatest([cv$, admin$], (isCvUploaded, isAdminOrManager) => {
isAllowed = isAdminOrManager ? true : isCvUploaded ? false : true;
return isAllowed;
}).pipe(
finalize(() => {
if (!isAllowed)
this.snackbarService.open(
'This profile has CV already created!',
'Info'
);
})
);
}
}
I have also experimented with the zip operator, but unfortunately, it did not yield the desired outcome.