我在尝试运行 ngserve 或 ngbuild 时遇到错误。错误消息指出:“router-outlet”不是已知元素。这是我的 Angular 应用程序的结构:
app.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { FeaturesComponent } from './features/features.component';
import { HowItWorksComponent } from './how-it-works/how-it-works.component';
import { UploadComponent } from './upload/upload.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomepageComponent,
FeaturesComponent,
HowItWorksComponent,
UploadComponent,
],
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot([]), // Import RouterModule.forRoot with an empty array
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
应用程序路由.module.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomepageComponent } from './homepage/homepage.component';
import { FeaturesComponent } from './features/features.component';
import { HowItWorksComponent } from './how-it-works/how-it-works.component';
import { UploadComponent } from './upload/upload.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomepageComponent },
{ path: 'features', component: FeaturesComponent },
{ path: 'how-it-works', component: HowItWorksComponent },
{ path: 'upload', component: UploadComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html:
<router-outlet></router-outlet>
app.component.ts:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'mri-scan-analyzer';
}```
I've been stuck on this error for a few hours now and none of the solutions I found on StackOverflow seem to work for me. I suspect it could be related to the order of imports in my app.module.ts file, but I'm relatively new to Angular and would appreciate any help.
您已经将
RouterModule
作为 AppRoutingModule
的一部分,因此请删除以下行!
...
imports: [
BrowserModule,
FormsModule,
// RouterModule.forRoot([]), // not needed!
AppRoutingModule,
],
...