Our routing guard for CanActivate
is functioning properly when navigating between links on the website. However, it fails when we do a full browser refresh, redirecting to the home page as if CanActivate
returns false.
Here is the code for my guard:
@Injectable()
export class PermissionCheckGuard implements CanActivate {
constructor(private userPermissionService: UserPermissionService) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
let permissionTag = route.data["permissionTag"] as string;
let hasPermission$ = this.userPermissionService.hasPermission(null, SubjectType.Site, permissionTag, null);
hasPermission$.subscribe(x => {
console.log(x);
});
return hasPermission$;
}
}
This is how I configured my router:
path: 'security/security-example', component: SecurityExampleComponent, canActivate: [PermissionCheckGuard], data: { permissionTag: 'Site_Permission_1' }
If relevant, here is the hasPermission
function:
public hasPermission(userId: string, subjectType: SubjectType, permissionTag: string, subjectId: string): Observable<boolean> {
if (userId == null) {
userId = 'Current';
}
const url = this.apiUrlBuilder.create('Security', 'Users', userId, 'Permission', {
permissionTag: permissionTag,
subjectType: subjectType,
subjectId: subjectId
});
return this.http.get(url)
.map<Response, boolean>((response: Response) => {
return <boolean>response.json();
})
.catch((error) => {
return this.errorHandlingService.ToNotification(error, this);
})
}
I have checked and ensured that the guard is returning an observable and the console log consistently displays true
. Could this be an Angular issue or is there a mistake in my code?