我正在开发一个由我公司的两个项目使用的包。在项目 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 {}
2 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
该注入令牌的目的是能够不使用注入器。
代替 =,使用此语法
constructor(@Inject('MESSAGE_SERVICE')protected service: YourInterface)
尽管如果您提供服务,我看不到使用注入令牌的意义。
吃鸡游戏
TA贡献1829条经验 获得超7个赞
您可以创建一个角度库,然后在任意数量的项目中使用它
以下是如何创建 angular2 库https://makina-corpus.com/blog/metier/2017/how-to-create-an-angular-library
使用 angular-cli https://medium.com/@nikolasleblanc/building-an-angular-4-component-library-with-the-angular-cli-and-ng-packagr-53b2ade0701e
添加回答
举报
0/150
提交
取消