Hello there!
I am currently working on an Angular 7 application that deals with time cards. One of the main features I have implemented is a CanActivate Guard for controlling access to certain components. The CanActivate code utilizes Observables to decide whether a user should be allowed entry or redirected.
timecardID: number;
constructor(private globals: Globals, private router: Router, private securityService: SecurityService) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | boolean {
if (next.params.timecardId) {
this.timecardID = +next.params.timecardId;
return this.hasAccessToTimecard();
}
return this.empNumber === this.globals.empNumber;
}
//Checking if current user has access to specific timecard
hasAccessToTimecard(): Observable<boolean | UrlTree> {
return this.securityService.hasRightsToTimecard(this.timecardID);
}
The following snippet shows the service being called:
private readonly HasRightsToTimecardURI = 'api/Security/HasRightsToTimecard';
private readonly HasRightsToEmployeeURI = 'api/Security/HasRightsToEmployee';
constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string, private router: Router) { }
//I don't like the use of router to navigate here. But without it, on false return the UrlTree isn't used for redirections.
public hasRightsToTimecard(timecardID: number): Observable<boolean | UrlTree> {
let parameters = new HttpParams();
parameters = parameters.set('timecardID', String(timecardID));
return this.http.get<boolean | UrlTree>(this.baseUrl + this.HasRightsToTimecardURI, { params: parameters }).pipe(
tap((result) => {
this.router.navigate(['/home']);
return result ? result : this.router.createUrlTree(['/home']);
})
);
}
I have confirmed that the logic works correctly, creating a UrlTree when the API returns false and handling true results properly.
However, I am facing issues with accessing the route through different methods:
- When using controls within the app's component, I have proper access as the guard allows me through
- If incorrect access is detected using controls in the component, the guard prevents me from proceeding to the route, which is expected behavior
- Directly typing the route URL in the browser results in a blank screen, instead of redirecting or showing content
If anyone could provide assistance, I would greatly appreciate it.
In addition, here's a relevant part of the route setup (excluding other details):
const routes: Routes = [
{
path: 'timecards', canActivateChild: [RightsGuard], children: [
{ path: 'edit/:timecardId', canActivate: [TimecardGuard], component: TimecardNewComponent }
]
}
];