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

Angular v15中独立Pipe注入Service报错:无BazPipe提供者

问题描述

在Angular v15中使用bootstrapApplication引导应用组件,在组件的ts文件中导入并在imports数组中声明了AppHeaderComponent;该组件通过foo = inject(FooService);注入了FooService,而FooService又注入了BazPipe。BazPipe是一个独立管道(配置了standalone: true),代码如下:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'baz',
  standalone: true,
})
export class BazPipe implements PipeTransform {
  constructor() {}

  transform(value) {
    return value;
  }
}

控制台抛出错误:

ERROR
Error: R3InjectorError(Environment Injector)[FooService -> BazPipe -> BazPipe]:
NullInjectorError: No provider for BazPipe!
错误原因

Angular的独立管道(standalone: true)的standalone配置仅表示该管道不需要在NgModule的declarations中声明,但它默认不会被自动注册为可注入的依赖服务。

当你在FooService中尝试注入BazPipe时,Angular的注入器无法找到BazPipe的提供者:管道本身的元数据没有配置providedIn来指定注入范围,也没有被添加到任何注入器的providers数组中,因此注入器无法实例化BazPipe并提供给FooService,最终抛出NullInjectorError。

补充解决方法

要解决这个问题,有两种常用方式:

  1. 在bootstrapApplication的配置中显式提供BazPipe:
bootstrapApplication(AppComponent, {
  providers: [
    FooService,
    BazPipe // 将管道添加到根注入器的提供者列表
  ]
});
  1. 在BazPipe的@Pipe装饰器中添加providedIn: 'root',让它成为根注入器的全局可注入依赖:
@Pipe({
  name: 'baz',
  standalone: true,
  providedIn: 'root' // 指定管道由根注入器提供
})
export class BazPipe implements PipeTransform {
  constructor() {}

  transform(value) {
    return value;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:20:41