我正在開發(fā)一個由我公司的兩個項目使用的包。在項目 A 中,只有在那里我們得到了這樣提供的消息服務(wù)core.module: { provide: 'MESSAGE_SERVICE', useClass: MessageService }在我的組件中,我需要注入這個服務(wù)。我正在使用injector. 然而get,接受字符串作為參數(shù)的方法已被棄用,所以我不能使用它,盡管它可以工作。當(dāng)我嘗試使用新的 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); }在不使用所述類的直接導(dǎo)入的情況下獲得我的服務(wù)的正確方法是什么?我想在項目 B 中創(chuàng)建一個模擬類,這樣我就可以使用MessageService類。但是,我想知道是否有更好的方法。編輯共享服務(wù)只是其他實現(xiàn)的基類,它是使用工廠提供的,因此其中沒有依賴注入。這是它的提供方式: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 {}
如何使用 angular 8 中的注入器注入使用注入令牌的服務(wù)
LEATH
2021-11-12 16:39:38