Angular路由失效仅显示空白页,请求技术排查与解决
路由失效、页面空白的排查修复方案
问题根源
你的路由无法正常工作、页面空白,主要是这几个原因:
- RouterModule未绑定自定义路由规则:你在
AppRootModule里只导入了RouterModule,但没把app.routes.ts里的routes配置关联进去,Angular根本不知道要使用哪些路由规则。 - 组件未在模块中声明:
AllArtistsComponent和AddArtistComponent没加到模块的declarations数组里,Angular无法识别这些组件。 - 重复导入冗余模块:模块的
imports里重复导入了FormsModule,属于无效冗余代码。 - 自定义模块未正确启动:Angular CLI默认生成根模块是
AppModule,你自行创建的AppRootModule未被设置为启动根模块,相当于没起作用。
修复步骤
方法一:修正自定义的AppRootModule
如果坚持使用自己创建的AppRootModule,修改代码如下:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; // 导入自定义路由配置 import { routes } from './app.routes'; // 导入所有用到的组件 import { AppComponent } from './app.component'; import { AllArtistsComponent } from './artists/all-artists/all-artists.component'; import { AddArtistComponent } from './artists/add-artist/add-artist.component'; @NgModule({ // 声明所有需要使用的组件 declarations: [ AppComponent, AllArtistsComponent, AddArtistComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule, // 绑定路由配置,forRoot表示这是根路由模块 RouterModule.forRoot(routes) ], exports: [ BrowserModule, FormsModule, HttpClientModule ], // 指定应用启动的根组件 bootstrap: [AppComponent] }) export class AppRootModule { }
然后打开main.ts,确保应用启动时加载这个模块:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppRootModule } from './app-root.module'; platformBrowserDynamic().bootstrapModule(AppRootModule) .catch(err => console.error(err));
方法二:使用默认AppModule(更省心)
Angular CLI默认生成AppModule,直接修改这个模块更简单,无需折腾自定义模块:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { routes } from './app.routes'; import { AppComponent } from './app.component'; import { AllArtistsComponent } from './artists/all-artists/all-artists.component'; import { AddArtistComponent } from './artists/add-artist/add-artist.component'; @NgModule({ declarations: [ AppComponent, AllArtistsComponent, AddArtistComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule, RouterModule.forRoot(routes) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
检查导航链接正确性
确认app.component.html中的导航链接使用了正确的routerLink指令:
<nav> <a routerLink="/">所有艺术家</a> <a routerLink="/add-artist">添加艺术家</a> </nav> <router-outlet></router-outlet>
若使用Angular 14+独立组件模式
这种模式无需模块,直接在main.ts中配置路由启动:
import { bootstrapApplication } from '@angular/platform-browser'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { AppComponent } from './app.component'; bootstrapApplication(AppComponent, { providers: [ provideRouter(routes) ] });
这种情况直接删除你自行创建的AppRootModule即可。
内容的提问来源于stack exchange,提问作者Youri
相关产品推荐
相关产品推荐

