Lazy loading is being used in my application to render pages.
{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] }
The problem arises when the user types www.mydomain.com/dashboard in the URL. The browser ends up rendering the dashboard page momentarily before redirecting to the login screen. How can I prevent any page from being rendered if the user is not logged in, and instead directly redirect them to the login page?
AuthGuard Class
export class AuthGuard implements CanActivate {
result: boolean = false;
auth: any;
outRes: any;
constructor(private _authService: JwtService, private _router: Router) {
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.outRes = this._authService.isAuthenticated();
if (this.outRes) {
this.outRes.subscribe(o => o ? true : this._authService.redirectToLogin());
return true;
} else {
this._authService.redirectToLogin();
return false;
}
}
}
Service Class
public isAuthenticated() {
if (!this.loggedIn)
this.redirectToLogin();
return this.httpClient.get<boolean>(`${this.settings.getApiSettings('uri')}/api/auth/IsTokenValid`, {
params: { token: this.getToken }
}).map( /// <<<=== use `map` here
(response) => {
if (response !== null) {
var receivedToken = response["securityStamp"];
var availableToken = localStorage.getItem('access_token');
//Check if received a refreshed token. (tokens are refreshed every 15 minutes)
if (receivedToken && receivedToken !== availableToken) {
localStorage.removeItem('access_token');
localStorage.setItem('access_token', response["securityStamp"]);
}
}
let data = response;
if (data == null)
return false;
else
return true;
}
);
}
redirectToLogin() {
localStorage.removeItem('access_token');
window.location.href = "./login";
}