You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular实现主页面API宕机时自动重定向至指定页面

Angular API服务器宕机时自动重定向至自定义页面的解决方案

一、全局HTTP错误拦截器(核心方案)

通过Angular的HttpInterceptor捕获所有API请求的失败状态,当检测到服务器不可达(如请求超时、DNS解析失败)或5xx类错误时,自动重定向到自定义页面。

  1. 生成拦截器文件
ng generate interceptor interceptors/api-error
  1. 修改拦截器代码,添加错误处理逻辑
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';
import { Router } from '@angular/router';

@Injectable()
export class ApiErrorInterceptor implements HttpInterceptor {

  constructor(private router: Router) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        // 匹配服务器宕机相关的错误类型
        const isServerDown = error.status === 0 || error.status >= 500;
        // 避免重复重定向
        if (isServerDown && !this.router.url.includes('/maintenance')) {
          this.router.navigate(['/maintenance']);
        }
        return throwError(() => error);
      })
    );
  }
}
  1. 在app.module.ts中注册拦截器
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ApiErrorInterceptor } from './interceptors/api-error.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ApiErrorInterceptor,
      multi: true
    }
  ]
})
export class AppModule {}

二、配置自定义页面路由

  1. 生成自定义维护页面组件
ng generate component pages/maintenance
  1. 在app-routing.module.ts中添加路由规则
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MaintenanceComponent } from './pages/maintenance/maintenance.component';
// 导入你的其他页面组件

const routes: Routes = [
  // 其他正常路由配置
  { path: 'maintenance', component: MaintenanceComponent },
  // 可选:用户访问不存在路径时,也跳转到维护页(按需调整)
  { path: '**', redirectTo: '/maintenance' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

三、快速启用维护模式(可选)

如果不想等待API请求失败再跳转,可在环境配置中添加开关,提前触发重定向:

  1. 修改environment.ts(开发环境)和environment.prod.ts(生产环境)
export const environment = {
  production: false, 
  basePath: 'demo.aplication.eu/api', 
  apiBasePath: 'demo.aplication.eu/repes/api', 
  cpiBasePath: 'demo.aplication.eu/cpi', 
  elisBasePath: 'ci.asano.ro/elisApi', 
  docmanBasePath: 'demo.aplication.eu/docmanApi', 
  googleMapsApiKey: 'AIzaSiDIV0uiLUobLB_JG1m4LVbccyQbu8DbfT0', 
  domain: 'demo.aplication.eu', 
  keycloakConfig: { 
    url: 'demo.aplication.eu/auth', 
    realm: 'ccdm', 
    clientId: 'ccdm-authz-client' 
  },
  // 添加维护模式开关
  maintenanceMode: false
};
  1. 创建路由守卫判断开关状态
    生成路由守卫:
ng generate guard guards/maintenance

修改守卫代码:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { environment } from '../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class MaintenanceGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    if (environment.maintenanceMode && !this.router.url.includes('/maintenance')) {
      this.router.navigate(['/maintenance']);
      return false;
    }
    return true;
  }
}
  1. 在路由中应用守卫
const routes: Routes = [
  { 
    path: 'dashboard', 
    component: DashboardComponent,
    canActivate: [MaintenanceGuard] // 给需要保护的路由添加守卫
  },
  { path: 'maintenance', component: MaintenanceComponent },
  { path: '**', redirectTo: '/maintenance' }
];

四、测试验证

  • 模拟服务器宕机:修改environment.ts中的basePath为无效地址(如invalid.server.com/api),启动项目后发起API请求,会自动跳转到维护页。
  • 测试维护模式:将maintenanceMode设为true,启动项目后直接进入维护页,无需等待API请求失败。

内容的提问来源于stack exchange,提问作者Militaru Razvan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 06:06:20