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
相关产品推荐
相关产品推荐

