'Angular2+: How to use a service in a library
Maybe I'm just plain stupid and do not understand what enno.void is referring to - or the question isn't really answered.
Regardless: I have a similar problem:
There is an existing app which I want my new library integrated in.
I know, there is a specific service in app which I need in library.
For type purposes, I've created an interface in library. But how can I use this fancy service app in library?
Following was my initial approach:
app.module.ts (the existing app)
import { MyLibModule } from 'my-lib';
import { FancyService } from './fancy.service';
...
imports: [
BrowserModule,
MyLibModule.forRoot(new FancyService()),
],
providers: [
FancyService
],
lib.module.ts (the new library)
import { FancyService } from './fancy-interface.service';
@NgModule({
declarations: [ MyLibComponent ],
exports: [ MyLibComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class MyLibModule
{
public static forRoot(fancyService: FancyService):
ModuleWithProviders<MyLibModule>
{
return {
ngModule: MyLibModule,
providers: [
{ provide: 'FancyService', useValue: fancyService}
]
};
}
}
That is working so far, but as you can see, I have to instantiate the requested service. Not cool. I wanted the same instance - not different ones.
As far as I've understood, you can only use that forRoot-method (or InjectionToken) if you have static values (which makes sense).
So my question is: how can I use FancyService with DI in my-lib?
Another approach was to use the Injector in the my-lib.component.ts
public constructor(private injector: Injector)
{
this.fancyService = injector.get('FancyService');
}
As expected, an NullInjectorError was thrown. But I don't really have another clue.
Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
