I am implementing a canActivate Guard that has a logic to redirect to the login site if the user is not logged in. So far, all the examples and fixes I've come across are dealing with a login page defined in Angular itself. In my case, login is on a separate subdomain.
The redirect is working as expected but because of the external redirect, restricted page displays in the browser and then the redirect starts.
I've tried both window.open and document through @inject.
Using Angular 5.2.5
This is my auth.guard.ts:
import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Router, CanActivate, CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { AlmVars } from '@alm/ngwebpack-vars/alm-vars.const';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
readonly almVars = AlmVars;
constructor(private router: Router, private cookieService: CookieService, @Inject(DOCUMENT) private document: any) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.cookieService.get('almVToken')) {
return true;
}
// this.document.location.href = '//login.' + this.almVars.hostname + '?referer=' + this.almVars.app;
window.open('//login.' + this.almVars.hostname + '?referer=' + this.almVars.app, '_self');
return false;
}
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppResolver } from './app.resolver';
import {AuthGuard} from './shared/alm-auth.guard';
import {ProfileComponent} from './profile/profile.component';
const appRoutes: Routes = [{
path: '',
component: ProfileComponent,
canActivate: [
AuthGuard
],
}];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes),
],
exports: [
RouterModule,
],
providers: [
AppResolver,
]
})
export class AppRoutingModule {
}