重定向到维护页面

时间:2020-04-16 11:21:25

标签: javascript angularjs

我正在寻找以角度方式将页面重定向到维护页面的方法,但是我是新手,并且正在研究用于打开维护模式的不同方法 我在这里找到了可能的解决方案:@批准的答案 Angular JS redirect to page within module config

但是我不知道如何实现它 如果有人可以解释它,我将不胜感激

1 个答案:

答案 0 :(得分:0)

使用authGuard可以解决此问题

auth-guard.service.ts文件:

import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuardMaintenance implements CanActivate {

  constructor(
    private authService: AuthService, private router: Router
  ) {}

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    if (this.authService.inMaintenance()) {
      alert('This Site Is Still Under Maintenance')
      this.router.navigate(['/maintenance']);
      return false;
    } else {
      this.router.navigate(['/']);
      return true;
    }
  }

}

auth.service文件:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor() { }

  inMaintenance() {
    return false;
    }
}

然后将其导入app.module.ts文件并将其添加到提供程序

然后将身份验证防护导入到app-routing.module.ts文件中,添加属性

canActivate: [AuthGuardMaintenance] 

到根路由 例如

export const routes: Routes = [
  { path: '', component: MainComponent, canActivate: [AuthGuardMaintenance] },
  { path: 'maintenance', component: MaintenanceViewComponent },
  { path: '**', component: PageNotFoundComponent },
 ];
相关问题