I faced the problem of document is not defined when I was trying to solve the issue of the login component appearing for a few seconds when I refresh the page. I see that this is bad behavior. When I tried to solve this problem with some code, I encountered the document is not defined error.
`import { Inject, Injectable } from ‘@angular/core’;
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from ‘@angular/router’;
import { LocalStorageServiceService } from ‘../Services/local-storage-service.service’;
import { DOCUMENT } from ‘@angular/common’;
@Injectable({
providedIn: ‘root’
})
export class AuthGuard implements CanActivate {
constructor(private router: Router, private localStorageService: LocalStorageServiceService,@Inject(DOCUMENT) private document: Document) { }
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise {
const loadingElement = document.createElement('div');
loadingElement.innerHTML = '<app-loading></app-loading>';
document.body.appendChild(loadingElement);
try {
const token = await this.localStorageService.getItem('token');
if (token) {
// User is authenticated, allow route activation
return true;
} else {
// User is not authenticated, navigate to authentication page and deny route activation
this.router.navigate(['/login']);
return false;
}
} finally {
document.body.removeChild(loadingElement);
}
}
}`
I tried this solution it solve the documenet not definied but the login component appear againn
`export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private localStorageService: LocalStorageServiceService,
@Inject(PLATFORM_ID) private platformId: Object
) { }
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise {
let loadingElement: HTMLDivElement | null = null;
// Check if running in the browser
if (isPlatformBrowser(this.platformId)) {
loadingElement = document.createElement('div');
loadingElement.innerHTML = '<app-loading></app-loading>';
document.body.appendChild(loadingElement);
}
try {
const token = await this.localStorageService.getItem('token');
if (token) {
// User is authenticated, allow route activation
return true;
} else {
// User is not authenticated, navigate to authentication page and deny route activation
this.router.navigate(['/login']);
return false;
}
} finally {
// Check again if running in the browser before trying to remove the element
if (isPlatformBrowser(this.platformId) && loadingElement) {
document.body.removeChild(loadingElement);
}
}
}
}`