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();
}
}
You are using different injection token then the one used in the module since your are importing sources directly with
expose it via public-api in your library, then use it via public api just like you do with the module
eg
and then it will work.
Right now you are expecting compiled entity in the library to be equal to entity that is compiled directly into your applicaiton, which will not work (class in the module is not the same class you are importing(compiling it again))