Problem:
I work in angular workspace and I import common.module.ts from library (library generated with ng generate library) to my app.module.ts, but when I inject CommonService in app.component.ts I get error:
main.ts:11 ERROR NullInjectorError: R3InjectorError(AppModule)[CommonService -> CommonService -> CommonService]: NullInjectorError: No provider for CommonService! There is an provider for CommonService in common.module.ts so I expect when I inject service in component no error should occure.
Code:
Library module 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 { } Application module 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(); } }
common.module.tslocated inside library (in your case)? Because this error only reproduced in case I importcommon.module.tsfrom library (library generated using cling generate library)providers. I think that injection token is different in both cases.providersarray of library module?