I have implemented a guard in my Angular application to validate user authorizations before granting access to a specific page. The guard makes an asynchronous API call to retrieve the necessary authorization information. While most of the time it works smoothly, I encountered a peculiar issue during performance testing on Chrome with Slow 3G throttling. The call made by the guard gets automatically canceled after approximately 445ms.
Below are the key sections of the code:
auth.service
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Authorization } from '@models';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
@Injectable()
export class AuthService {
constructor(private http: HttpClient) {}
getAuthorizations(id: number): Observable<Authorizations> {
return this.http
.get(`/api/authorizations`)
.pipe(
map(res => {
return !!res && (<any>res).data.authorizedActions
? (<any>res).data.authorizedActions
: null;
})
);
}
}
app.module
export const appRoutes: Routes = [
{
path: '',
component: HomeComponent,
},
{
path: 'budget',
canActivate: [BudgetGuard],
loadChildren: () => import('./budget').then(m => m.BudgetModule),
},
];
budget.guard
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
import { AuthorizedBusinessAction } from '@tproj/models';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from '../auth.service';
import { of } from 'rxjs';
@Injectable()
export class BudgetGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
const userId = route.params.userId;
return this.authService
.getAuthorizations(userId)
.pipe(map(auth => {
if (auth.userIsAuthorized) {
return auth.userIsAuthorized;
}
this.router.navigate([`/`]);
}));
}
}
If anyone has any insights or suggestions, I would greatly appreciate it. Thank you!