You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18使用[routerLink]报错:NullInjectorError缺少ActivatedRoute提供者

问题根源

  1. 路由提供者未正确注册:你的main.ts没有使用定义好的appConfig(其中包含provideRouter(routes)),导致Angular的路由服务(包括ActivatedRoute)没有被注入到应用依赖中。
  2. 组件不在路由上下文内:AppComponent直接导入并渲染了BookComponent,而非通过router-outlet加载,这使得BookComponent脱离了路由上下文,使用routerLink时无法找到ActivatedRoute的提供者。

修复步骤

1. 修改main.ts,合并应用配置

将appConfig的提供者和HttpClientModule合并到bootstrapApplication中,确保路由服务被正确注册:

/// <reference types="@angular/localize" />

import { bootstrapApplication } from "@angular/platform-browser";
import { AppComponent } from "./app/app.component";
import { HttpClientModule } from "@angular/common/http";
import { importProvidersFrom } from "@angular/core";
import { appConfig } from "./app/app-config"; // 导入appConfig

bootstrapApplication(AppComponent, {
  providers: [
    ...appConfig.providers, // 合并路由提供者
    importProvidersFrom(HttpClientModule)
  ],
}).catch((err) => console.error(err));

2. 修改AppComponent,移除直接渲染的BookComponent

让BookComponent通过路由的router-outlet来加载,确保组件处于路由上下文:

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [HeaderComponent, FooterComponent, RouterOutlet], // 移除BookComponent的导入
  template: `
    <app-header></app-header>
    <router-outlet></router-outlet> <!-- 由路由加载BookComponent -->
    <app-footer></app-footer>
  `,
})
export class AppComponent {
  books: Book | undefined;
}

额外说明

  • 你的路由配置app.routes.ts已经正确设置了默认路径指向BookComponent,修改后应用启动时会自动通过router-outlet加载它。
  • 修复后,BookComponent内的[routerLink]会处于路由上下文,能够正常获取ActivatedRoute的提供者,不会再触发NullInjectorError,同时书籍列表也能正常渲染。

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:44:50