我正在实现一个 canActivate Guard,它具有在用户未登录时重定向到登录站点的逻辑。到目前为止,我遇到的所有示例和修复都在处理 Angular 本身定义的登录页面。就我而言,登录位于单独的子域上。
重定向按预期工作,但由于外部重定向,浏览器中显示受限页面,然后重定向开始。
我已经通过@inject 尝试了 window.open 和文档。
使用 Angular 5.2.5
这是我的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;
}
}
应用程序路由.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 {
}