Search code examples
angularangular-guards

CanActivate returns me to a blank page instead of redirecting


My guard returns me to a blank page instead of redirecting me. Also my root is not a blank page it should send me to login as well. This happens when I go to any supervisor page.

These are my routes:

export const appRoutes: Routes = [
  {path: '', component: LoginScreenComponent},
  {path: 'login', component: LoginScreenComponent},
  {path: 'student', component: StudentDownloadComponent, canActivate: [StudentGuard]},
  {path: 'student/download', component: StudentDownloadComponent, canActivate: [StudentGuard]},
  {path: 'student/upload', component: StudentUploadComponent, canActivate: [StudentGuard]},
  {path: 'supervisor', component: SupervisorUploadComponent, canActivate: [SupervisorGuard]},
  {path: 'supervisor/upload', component: SupervisorUploadComponent, canActivate: [SupervisorGuard]},
  {path: 'supervisor/logs', component: SupervisorLogsComponent, canActivate: [SupervisorGuard]},
  {path: 'supervisor/overzicht', component: SupervisorOverzichtComponent, canActivate: [SupervisorGuard]}
  ];

And this is my guard:

@Injectable()
export class SupervisorGuard implements CanActivate {
  constructor(private supervisor: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.supervisor.getSupervisorLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

The service:

@Injectable()
export class AuthService {
  private isStudentLoggedIn;
  private isSupervisorLoggedIn;

  constructor() {
    this.isStudentLoggedIn = false;
    this.isSupervisorLoggedIn = false;
  }

  setStudentLoggedIn() {
    this.isStudentLoggedIn = true;
  }

  getStudentLoggedIn() {
    return this.isStudentLoggedIn();
  }

  setSupervisorLoggedIn() {
    this.isSupervisorLoggedIn = true;
  }

  getSupervisorLoggedIn() {
    return this.isSupervisorLoggedIn();
  }

}

Solution

  • In the service, you're trying to invoke isSupervisorLoggedIn as if it's a function, but it's just a boolean.

    You should do return this.isSupervisorLoggedIn; instead