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

Angular 17独立项目路由报错:window is not defined

问题解决:Angular 17路由中window未定义错误

问题场景

从Angular 16非独立项目升级至17并迁移为独立项目后运行正常,新建Angular 17项目复制迁移内容,将app-routing.module.ts内容复制到app.routes.ts并注释NgbModule相关部分后,出现如下错误:

10.07.54 [vite] Internal server error: window is not defined
at eval (C:\Code\bengkel_web_17\src\app\app.routes.ts:27:18)
at async instantiateModule (file:///C:/Code/bengkel_web_17/node_modules/vite/dist/node/chunks/dep-k5wXcrSr.js:54897:9) (x2)

对应的路由代码:

{ path: '', 
  redirectTo:  window.screen.width > 768 ? "home" : "mobile", 
  pathMatch: 'prefix'
}

VSCode中window.screen.width有代码提示,但运行时仍报错。

解决方法

问题根源是Angular 17的独立路由配置会在服务端预渲染/初始化阶段执行,此时Node.js环境中不存在window对象,不能直接在静态路由配置中使用window,需改用以下两种方案:

方案1:用路由守卫实现动态重定向

把根路径的重定向逻辑移到CanActivateFn守卫中,确保仅在浏览器环境执行:

// app.routes.ts
import { CanActivateFn, Router, Routes } from '@angular/router';
import { inject } from '@angular/core';

export const mobileRedirectGuard: CanActivateFn = () => {
  const router = inject(Router);
  // 先判断是否处于浏览器环境
  const isMobile = typeof window !== 'undefined' && window.screen.width <= 768;
  router.navigate([isMobile ? 'mobile' : 'home']);
  return false; // 阻止原空路径路由激活
};

export const routes: Routes = [
  { path: '', canActivate: [mobileRedirectGuard] },
  { path: 'home', component: HomeComponent },
  { path: 'mobile', component: MobileComponent },
  // 其他路由配置...
];

方案2:在根组件初始化时处理重定向

如果项目不涉及服务端渲染,可在AppComponent的初始化钩子中处理:

// app.component.ts
import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit(): void {
    // 仅当当前路径为空时执行重定向
    if (this.router.url === '/') {
      const targetRoute = window.screen.width > 768 ? 'home' : 'mobile';
      this.router.navigate([targetRoute]);
    }
  }
}

同时修改路由配置,移除原静态重定向规则:

// app.routes.ts
export const routes: Routes = [
  { path: '', component: AppComponent },
  { path: 'home', component: HomeComponent },
  { path: 'mobile', component: MobileComponent },
  // 其他路由配置...
];

补充提示

  • 所有涉及window的代码都要先判断typeof window !== 'undefined',避免服务端环境报错;
  • 如果项目启用SSR,建议通过请求头的User-Agent判断设备类型,而非依赖window.screen.width。

内容的提问来源于stack exchange,提问作者rheza 555

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:55:12