亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

LEATH 2021-11-12 16:39:38
我正在開發一個由我公司的兩個項目使用的包。在項目 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)

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


查看完整回答
反對 回復 2021-11-12
?
吃雞游戲

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


查看完整回答
反對 回復 2021-11-12
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號