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

Angular 4路由按窗口宽度动态分配组件时报TS2322错误如何解决

Angular路由动态分配组件TS2322错误修复方案

错误核心原因

你误将Angular模板的插值语法{{ }}用在了TypeScript逻辑文件中,TypeScript会将{{ routingTest }}解析为一个包含routingTest属性的对象,和Route接口要求的component字段类型不匹配,因此抛出TS2322错误。

修正后完整代码

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
// 替换为你实际的组件导入路径
import { Testpage1Component } from './pages/testpage1/testpage1.component';
import { Testpage2Component } from './pages/testpage2/testpage2.component';
import { Testpage3Component } from './pages/testpage3/testpage3.component';

const width  = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
console.log("this is the width (responsive),", width)
// 类型用小写any,也可以声明为Type<any>(需要从@angular/core导入Type)
let routingTest: any;
    
if (width > 764) {
  routingTest = Testpage1Component
} else { 
  routingTest = Testpage2Component
}
console.log("routing file test", width , routingTest)

const routes: Routes = [
  // redirectTo需要搭配pathMatch使用,避免非预期重定向
  { path: 'home', redirectTo: '', pathMatch: 'full' },
  { path: 'test1', component: Testpage2Component},
  { path: 'test', component: Testpage3Component},
  // 直接引用变量,删除双大括号即可
  { path: '**', component: routingTest }
];

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

额外优化提示

  • 当前实现仅会在应用首次加载时检测一次窗口尺寸,用户手动调整窗口大小不会触发组件切换,如果需要响应尺寸变化,可以采用路由守卫+动态组件加载的方案实现。
  • 通配符路由**必须放在路由数组的最后位,否则会优先匹配通配符规则,覆盖其他正常路由。

内容的提问来源于stack exchange,提问作者Sandip Dhillon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:36:03