I'm currently facing a challenge in sharing a service from the npm package that I created using ng g library
with my Angular hosting application. While I have experience in linking components and directives, I'm a bit lost when it comes to services.
Within the library, I have the following key files:
- authentication.service.ts
- authentication.module.ts
All of these are listed in the public-api.ts
file and successfully imported into my hosting app.
authentication.service.ts: (I've experimented without using providedIn: 'root'
as well)
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
...
}
authentication.module.ts:
@NgModule({
})
export class AuthenticationModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: AuthenticationModule,
providers: [AuthenticationService]
};
}
}
hosting app's app.module.ts:
import { AuthenticationService } from '@custom/lib';
import { AuthenticationModule } from '@custom/lib';
export function appInitFactory(
injector: Injector,
authenticationService: AuthenticationService,
configService: ConfigService
): any {
return () =>
loadConfig(configService, authenticationService)
.then(() => checkLogIn(injector, authenticationService));
}
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
AuthenticationModule.forRoot()
],
providers: [
AuthenticationService,
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
{
provide: APP_INITIALIZER,
useFactory: appInitFactory,
deps: [Injector, AuthenticationService, ConfigService],
multi: true,
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
I'm keen on injecting the AuthenticationService
into the appInitFactory
because this is where I load application configuration from a JSON file and perform authentication validation before the hosting app initializes.
The error message I encounter reads as follows:
core.js:15723 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthenticationService]:
StaticInjectorError(Platform: core)[AuthenticationService]:
NullInjectorError: No provider for AuthenticationService!
Error: StaticInjectorError(AppModule)[AuthenticationService]:
StaticInjectorError(Platform: core)[AuthenticationService]:
NullInjectorError: No provider for AuthenticationService!
at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get
If anyone has insights on what might be causing this error, your assistance is greatly appreciated.