我正在开发一个由我公司的两个项目使用的包。在项目 A 中,只有在那里我们得到了这样提供的消息服务core.module:
{
provide: 'MESSAGE_SERVICE',
useClass: MessageService
}
在我的组件中,我需要注入这个服务。我正在使用injector. 然而get,接受字符串作为参数的方法已被弃用,所以我不能使用它,尽管它可以工作。当我尝试使用新的 API 时,InjectionToken我总是未定义。这是我的代码:
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);
}
在不使用所述类的直接导入的情况下获得我的服务的正确方法是什么?我想在项目 B 中创建一个模拟类,这样我就可以使用MessageService类。但是,我想知道是否有更好的方法。
编辑
共享服务只是其他实现的基类,它是使用工厂提供的,因此其中没有依赖注入。这是它的提供方式:
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 {}
临摹微笑
吃鸡游戏
相关分类