Angular路由类型不匹配错误:如何修复该类型赋值问题?
嘿,这个问题我之前碰到过好多次,核心就是Angular路由配置的字段用错了,咱们一步步来解决:
首先看你遇到的具体错误提示:
类型"({path: string; component: Route [];} | {path: string; component: Route []; canActivate: (typeof ..."无法分配给类型"Route []"。类型"{path: string; component: Route [];} | {path: string; component: Route []; canActivate: (typeof ..."无法分配给"Route"类型。类型"{path: string; component: Route [];}"无法分配给"Route"类型。"component"属性类型不兼容。类型"Route []"无法分配给类型"type
"。类型"Route []"中不存在"apply"属性。
再看你的代码里的**routes**常量:
import { Routes } from '@angular/router'; import { SignInRoutes } from '../layout/sign-in/index'; import { LayoutRoutes } from '../layout/index'; import { SignInComponent } from '../layout/sign-in/sign-in.component'; import { AuthGuard } from '../shared/guards/auth.guard'; export const <span style="color:red">routes</span>: Routes = [ { path: 'sign_in', component: SignInRoutes }, { path: 'layout', component: LayoutRoutes, canActivate: [AuthGuard] }, { path: '**', component: SignInComponent } ];
问题出在哪?
SignInRoutes和LayoutRoutes本身是路由数组(比如你应该是在其他文件里定义了const SignInRoutes: Routes = [...]),但你把它们直接赋值给了component字段——Angular里component字段要求的是单个组件类,不是路由数组,这就导致了类型不匹配的错误。
如果要嵌套子路由,咱们得用children字段,而不是component。
修复后的代码示例
我假设你有对应的布局组件(比如LayoutComponent),如果没有的话可以根据实际情况调整:
import { Routes } from '@angular/router'; import { SignInRoutes } from '../layout/sign-in/index'; import { LayoutRoutes } from '../layout/index'; import { SignInComponent } from '../layout/sign-in/sign-in.component'; import { LayoutComponent } from '../layout/layout.component'; // 假设你有这个布局组件 import { AuthGuard } from '../shared/guards/auth.guard'; export const routes: Routes = [ { path: 'sign_in', // 用children嵌套sign_in的子路由 children: SignInRoutes, // 如果需要父路由显示SignInComponent,就加上这个;如果SignInRoutes里已经包含了该组件的路由,可以去掉 component: SignInComponent }, { path: 'layout', // 指定布局组件作为父路由的显示组件 component: LayoutComponent, canActivate: [AuthGuard], // 嵌套layout下的子路由 children: LayoutRoutes }, // 建议用redirectTo替代直接绑定组件,路由重定向更规范 { path: '**', redirectTo: 'sign_in' } ];
如果SignInRoutes里已经配置了SignInComponent的路由,那sign_in的父路由可以简化成:
{ path: 'sign_in', children: SignInRoutes }
额外小提示
- 确保
SignInRoutes和LayoutRoutes里的路由路径是相对路径(不要以/开头,否则会变成绝对路径,脱离父路由的上下文)。 - 如果父路由只是作为子路由的容器,不需要显示任何内容,可以设置
component: null,或者加上redirectTo指向默认子路由(比如redirectTo: 'layout/dashboard')。
内容的提问来源于stack exchange,提问作者user9750993

