I'm developing a package that is used by two projects in my company.
In project A and only there we got a message service that is provided in core.module like this:
{
provide: 'MESSAGE_SERVICE',
useClass: MessageService
}
In my component, I need to inject this service. I'm doing it using injector. However the method get that accepts a string as a parameter is deprecated so I cannot use it, although it works. When I try to use a new API with InjectionToken I always get undefined.
Here's my code:
protected messageService: any;
constructor(protected injector: Injector) {
const messageServiceInjectionToken = new InjectionToken('MESSAGE_SERVICE');
// i get null
this.messageService = this.injector.get<any>(messageServiceInjectionToken, null, InjectFlags.Optional);
// It works but method is deprecated
this.messageService = this.injector.get('MESSAGE_SERVICE', null);
// It works but I cannot use MessageService class directly as it is not present in application B
this.messageService = this.injector.get(MessageService);
}
What is the proper way to get my service without using direct imports of said class?
I thought of creating a mock class in project B so I would be able to use MessageService class. However, I'd like to know if there's a better way.
EDIT
The shared service is just a base class to other implementations, it is provided using a factory so there's not dependency injection in it. This is how it is provided:
export function parentServiceFactory(platformService: PlatformService, injector: Injector) {
if (platformService.isIOS) {
return new IosChildService(injector);
}
if (platformService.isAndroid) {
return new AndroidChildService(injector);
}
return new DesktopChildService(injector);
}
@NgModule({
providers: [
{
provide: ParentService,
useFactory: parentServiceFactory,
deps: [PlatformService, Injector]
}
]
})
export class SharedModule {}