簡體   English   中英

如何使用不同的服務注入以角度創建可重用組件?

[英]how to create a reusable component in angular with different service injection?

他們說組件應該是可重用的,但我不知道如何使我的案例可重用? 我想要一個用於在服務器上確認某些內容的組件?

@Component({
    selector: 'app-confirm',
    template: '<button (Click)="confirm()">'

})
export class ConfirmComponent {
 constructor(private confirmService: ConfirmService){}
 confirm(){
  this.confirmService.confirm();
 }
}

現在,如果我想在其他地方使用它,如何更改注入到此類中的確認服務我知道我可以在組件裝飾器中定義它,以便它將我想要的內容作為 confirmService 注入到此類中,但是然后這個服務是為每個組件創建的?

編輯

當我自己處理依賴注入時,我會做這樣的事情:

class ConfirmComponent{
 confirmService: ConfirmServiceInterface;
 constructor(confirmService: ConfirmServiceInterface){
   this.confirmService = confirmService;
 }
}

第一次使用:

new ConfirmComponent(a);

第二種用途:

new ConfirmComponent(b);

我想知道如何在角度上做到這一點?

如果您想要做的是根據您所在的位置以不同的方式提供服務,那么我將定義一個服務的不同實現繼承的 SuperClass。 讓我們稱它為 SuperClass 然后在組件中而不是 ConfirmService 我注入 SuperClass。 接下來,您只需在不同的模塊中以不同的方式提供它:

// module 1
{provide: SuperClass, useClass: ConfirmServiceImplementation}

// module 2
{provide: SuperClass, useClass: ConfirmServiceAnotherImplementation}

暫無
暫無

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

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