我的工作基于 Angular.io 上提供的教程 Tour of Heroes 教程。
该应用程序是使用以下命令创建的:
ng new toh --no-standalone --routing --ssr=false
我知道“独立”是新的默认设置,但我选择不使用它,因为我的公司正在使用
15.2.2
。
但是我遇到了一个我无法解决的问题,它从第 5 章(路由)开始。
按照指示添加
app-routing.module.ts
文件后,系统告诉我将 router-outlet
添加到我的 app.component.html
文件中;一旦我这样做了,我应该能够浏览到/heroes
(完整的网址:http://localhost:4200/heroes)并查看前面章节中构建的英雄列表。
但是控制台出现以下错误:
main.ts:6 ERROR Error: NG04002: Cannot match any routes. URL Segment: 'heroes'
at Recognizer.noMatchError (router.mjs:3654:12)
at router.mjs:3687:20
at catchError.js:10:39
at OperatorSubscriber2._this._error (OperatorSubscriber.js:25:21)
at Subscriber2.error (Subscriber.js:43:18)
at Subscriber2._error (Subscriber.js:67:30)
at Subscriber2.error (Subscriber.js:43:18)
at Subscriber2._error (Subscriber.js:67:30)
at Subscriber2.error (Subscriber.js:43:18)
at Subscriber2._error (Subscriber.js:67:30)
Promise.then (async)
(anonymous) @ main.ts:6
Show 26 more frames
heroes
和 /heroes
pathMatch: 'full'
添加到路线定义中。HeroesComponent
定义显式添加到此文件中的 imports
数组中。FWIW,在我注意到控制台错误之前,我尝试跳过它并创建 DashboardComponent 并添加导航按钮。但无论我手动浏览到
/heroes
还是单击按钮将我带到那里,都会发生此错误。
这是完整的
src/app/app-routing.module.ts
文件。
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HeroesComponent } from './heroes/heroes.component';
const routes: Routes = [
{ path: 'heroes', component: HeroesComponent, },
]
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
这是我的
package.json
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/router": "^17.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.0.8",
"@angular/cli": "^17.0.8",
"@angular/compiler-cli": "^17.0.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.2.2"
}
它不是通往英雄组件的路径。检查线路
import { HeroesComponent } from './heroes/heroes.component';
路径是否有意义。然后看
{ path: 'heroes', component: HeroesComponent, },
名称大小写相符吗?为什么最后有一个逗号,但没有其他项目。
还提供默认的全部路由来重定向到起始页,这是使用您提供的唯一路由:
{ path: '**', redirectTo: 'heroes' }