Angular中RouterLink无法跳转及@NgModule冲突错误求助
解决Angular页面跳转报错及路由配置问题
我帮你拆解下这两个报错的核心原因,然后一步步修复,让你的页面能正常跳转:
第一个报错:Two incompatible decorators on class @NgModule error
这个错误是因为你把模块专用的@NgModule装饰器错误地用在了组件类上!@NgModule是用来定义Angular模块的,而组件类必须用@Component装饰器来标记——你完全搞混了模块和组件的定义方式。
第二个报错:The class 'ShoppingCartComponent' is listed in the declarations...
你的ShoppingCartComponent根本没有添加@Component装饰器,Angular无法识别它是一个组件,所以在AppModule的declarations数组里注册它时就会报错。
现在开始一步步修复:
1. 重构shopping-cart.component.ts为正确的组件结构
把错误的模块装饰器移除,添加组件必备的@Component,同时补全类定义(你之前的代码里甚至都没写组件类的声明!):
import { Component } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; // 组件必须用@Component装饰器,指定选择器和模板路径 @Component({ selector: 'app-shopping-cart', templateUrl: './shopping-cart.component.html' // 确保路径和你的文件结构匹配 }) export class ShoppingCartComponent { // 构造函数放在类内部 constructor(public router: Router, private route: ActivatedRoute) {} // 跳转方法也放在类内部 public checkOut(): void { // 两种跳转方式选其一即可,路径要匹配路由配置 this.router.navigate(['/check-out'], { relativeTo: this.route }); // 或者 this.router.navigateByUrl('/check-out'); } }
2. 修复AppModule的配置问题
- 首先要把修复后的
ShoppingCartComponent导入并注册到declarations数组 - 移除重复的
RouterModule导入(AppRoutingModule已经包含了RouterModule的导出,重复导入会导致冲突) - 别忘了添加
BrowserModule——这是Angular浏览器应用的基础模块,必须导入:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { CheckOutComponent } from './check-out/check-out.component'; import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component'; // 导入购物车组件 @NgModule({ declarations: [ ShoppingCartComponent, // 现在可以正确注册这个组件了 CheckOutComponent ], imports: [ BrowserModule, // 必备基础模块 AppRoutingModule // 只需要导入路由模块即可,无需单独导入RouterModule ], providers: [], bootstrap: [ShoppingCartComponent] // 这里换成你的根组件(比如AppComponent,如果你有的话) }) export class AppModule { }
3. 优化模板的跳转逻辑
你的模板里用<a>包裹按钮且设置了type="submit",会触发表单默认提交行为(可能导致页面刷新),建议优化成以下两种方式之一:
<!-- 方式一:用表单提交触发跳转 --> <form (ngSubmit)="checkOut()"> <button type="submit">Check Out</button> </form> <!-- 方式二:直接用routerLink跳转,更简洁,避免表单提交 --> <a routerLink="/check-out"> <button type="button">Check Out</button> </a>
注意:不要同时混用
routerLink和click事件,避免不必要的冲突。
4. 验证CheckOutComponent的正确性
确保你的CheckOutComponent也是一个合法的Angular组件,比如check-out.component.ts要有@Component装饰器:
import { Component } from '@angular/core'; @Component({ selector: 'app-check-out', templateUrl: './check-out.component.html' }) export class CheckOutComponent { }
做完这些修改后,你的应用应该就能正常跳转到/check-out页面了。核心要记住:组件用@Component,模块用@NgModule,不要混淆;所有组件必须在模块的declarations里正确注册;路由模块只需要在根模块导入一次。
内容的提问来源于stack exchange,提问作者Maureen Moore
相关产品推荐
相关产品推荐

