簡體   English   中英

如何在 angular 8 中使用注入器注入使用注入令牌的服務

[英]How to inject service that is using injection token using injector in angular 8

我正在開發我公司的兩個項目使用的 package。 在項目 A 中,只有我們在core.module中提供了一個消息服務,如下所示:

        {
          provide: 'MESSAGE_SERVICE',
          useClass: MessageService
        }

在我的組件中,我需要注入此服務。 我正在使用injector來做這件事。 但是,接受字符串作為參數的方法get已被棄用,因此我無法使用它,盡管它有效。 當我嘗試使用帶有InjectionToken的新 API 時,我總是不確定。 這是我的代碼:

  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);
  }

在不使用直接進口的 class 的情況下獲得我的服務的正確方法是什么? 我想在項目 B 中創建一個模擬 class,這樣我就可以使用MessageService class。 但是,我想知道是否有更好的方法。

編輯

共享服務只是其他實現的基礎 class,它是使用工廠提供的,因此其中沒有依賴注入。 它是這樣提供的:


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 {}

該注入令牌的目的是能夠不使用注入器。

而是 =,使用此語法

constructor(@Inject('MESSAGE_SERVICE')protected service: YourInterface)

盡管如果您提供服務,我看不出使用注入令牌的意義。

您可以創建一個 angular 庫,然后在任意數量的項目中使用它

以下是如何創建 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM