Angular路由无法正常运行,请问我哪里操作有误?
Let's walk through the likely problems with your code and configuration step by step:
1. Incomplete Class Export (Critical Error)
The most immediate issue in your code is that you didn't finish defining the routing module class. Your line export class... is truncated, which will cause a compilation error and prevent Angular from recognizing your routing module entirely.
Fix it by completing the class definition:
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [] }) export class AppRoutingModule { } // Add this complete class definition
2. Missing <router-outlet> in Root Component
Angular needs a placeholder to render the components matched by your routes. If your root component (usually app.component.html) doesn't include the <router-outlet> tag, the routed components will never appear on the page.
Add this to app.component.html:
<router-outlet></router-outlet>
3. Ensure AppRoutingModule is Imported in AppModule
Your main application module (AppModule) must import the AppRoutingModule for the routing rules to take effect. Double-check that your AppModule includes it in the imports array:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; // Import the routing module import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, AppRoutingModule // Make sure this is present ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
4. Minor Syntax Fix (Optional but Recommended)
Your routes array definition is missing a trailing semicolon. While some compilers might overlook this, it's best practice to include it to avoid potential parsing issues:
const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'features', component: FeaturesComponent } ]; // Add this semicolon
Start with fixing the incomplete class export first—this is the most likely cause of your routing not working at all. Then verify the other points if the issue persists.
内容的提问来源于stack exchange,提问作者Laurens Mäkel

