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

Angular导入类库模块后注入CommonService报NullInjectorError错误

Angular类库服务注入报错:NullInjectorError: No provider for CommonService!

在Angular工作区中,通过ng generate library生成类库,将类库中的common.module.ts导入到主应用的app.module.ts后,在app.component.ts中注入CommonService时出现以下错误:

main.ts:11 ERROR NullInjectorError: R3InjectorError(AppModule)[CommonService -> CommonService -> CommonService]: 
  NullInjectorError: No provider for CommonService!

已在common.module.ts中配置CommonService的提供者,但注入时仍报错。

代码示例

类库模块 common.module.ts

import { NgModule } from '@angular/core';
import { CommonComponent } from './common.component';
import { HttpClientModule } from '@angular/common/http';
import { CommonService } from './common.service';

@NgModule({
    declarations: [],
    imports: [],
    exports: [],
    providers: [
        CommonService
    ]
})
export class CommonModule {

}

应用模块 app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { CommonModule } from 'common';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        CommonModule
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

app.component.ts

import { Component } from '@angular/core';
import { CommonService } from '../../../common/src/lib/common.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.less']
})
export class AppComponent {

    constructor(private common2: CommonService) {
    }
}

common.service.ts

@Injectable()
export class CommonService {
  constructor() {
    this.initProps();
  }
}

解决方案

  • 修正服务导入路径:app.component.ts中直接引用了类库源码路径,导致Angular无法关联到模块中注册的提供者。应改为从类库的官方导出入口导入:

    import { CommonService } from 'common';
    
  • 确保类库导出服务:在类库的public-api.ts文件中显式导出CommonService和CommonModule,让主应用能正确识别类库的导出内容:

    // common/src/public-api.ts
    export * from './lib/common.service';
    export * from './lib/common.module';
    
  • 构建类库:首次创建或修改类库后,执行ng build common编译类库,确保主应用引用的是编译后的类库代码,而非源码文件。

  • 可选:全局注册服务:如果希望服务无需依赖模块导入即可全局使用,可以修改CommonService的@Injectable装饰器,添加providedIn: 'root'配置,这样无需在模块的providers数组中注册:

    @Injectable({
      providedIn: 'root'
    })
    export class CommonService {
      constructor() {
        this.initProps();
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:55:30