Angular路由配置编译报错:无法找到指定组件
解决Angular路由编译错误
问题原因
编译报错是因为你在路由配置里使用了LoginComponent、ForgetPasswordComponent、NotFoundComponent,但没有在AppRoutingModule中导入这些组件;另外路由顺序也存在问题,会导致根路径重定向失效。
解决步骤
- 导入缺失的组件
在AppRoutingModule的导入区域,添加对应组件的导入语句,路径要和你的组件实际文件位置匹配,示例如下:
import { LoginComponent } from './login/login.component'; import { ForgetPasswordComponent } from './forget-password/forget-password.component'; import { NotFoundComponent } from './not-found/not-found.component';
- 修正路由顺序
Angular路由按匹配顺序执行,**通配符路由必须放在最后,否则会优先匹配它,导致根路径的重定向规则无法生效。调整后的路由数组如下:
const routes: Routes = [ {path: '' , redirectTo : '/login', pathMatch: 'full'}, {path: 'login', component: LoginComponent}, {path:'forget-password', component: ForgetPasswordComponent}, {path:'**', component: NotFoundComponent} ];
修改后的完整代码
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; // 导入所需组件 import { LoginComponent } from './login/login.component'; import { ForgetPasswordComponent } from './forget-password/forget-password.component'; import { NotFoundComponent } from './not-found/not-found.component'; const routes: Routes = [ {path: '' , redirectTo : '/login', pathMatch: 'full'}, {path: 'login', component: LoginComponent}, {path:'forget-password', component: ForgetPasswordComponent}, {path:'**', component: NotFoundComponent} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
内容的提问来源于stack exchange,提问作者Shambhavi
相关产品推荐
相关产品推荐

