簡體   English   中英

Angular - 服務注入

[英]Angular - Service injection

我正在嘗試添加一個應在應用程序啟動時實例化的服務 ( modal-dialog.service )。 我使用providedIn: 'root'屬性將它添加到我的常規服務文件夾中。 該服務必須在<body>標記中注入模態對話框,並且必須接受要在模態對話框中呈現的組件類型:

/**
 * Inject a dialog to the body.
 * @param dialogClass Class of the dialog.
 * @param configureDialog Configuration function for the dialog.
 */
public injectDialogToBody<T>(dialogClass: Type<T>, configureDialog: (dialogRef: ComponentRef<T>) => void): ComponentRef<T> {
    const factory = this._componentFactoryResolver.resolveComponentFactory(dialogClass);
    var dialogRefComponent = factory.create(this._injector);
    this._applicationRef.attachView(dialogRefComponent.hostView);
    configureDialog(dialogRefComponent);
    var dom = (dialogRefComponent.hostView as EmbeddedViewRef<any>).rootNodes[0];
    document.body.appendChild(dom);
    return dialogRefComponent;
}

我面臨的問題是,當我從一個模塊中調用這個injectDialogToBody方法時,該方法將一個組件傳遞給該模塊中的一個組件,因此它顯示在模式對話框中,我收到錯誤“找不到 XXXComponent 的組件工廠。你有嗎?將它添加到@NgModule.entryComponents? ”。

將此modal-dialog.service移動到modules文件夾內的一個公共模塊並將其添加到該模塊的提供者中可以解決問題。 如果放置在常規服務文件夾內(模塊文件夾外)並使用providedIn: 'root'為什么服務不能識別組件的類型?

您必須將 DialogComponent 添加到聲明它的模塊的entryComponents中。

遵循 Angular 文檔: https : //angular.io/guide/dynamic-component-loader#dynamic-component-loader

你必須像這個例子一樣: https : //angular.io/guide/dynamic-component-loader#resolving-components

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    DialogComponent
  ],
  exports: [
    DialogComponent
  ],
  entryComponents: [
    DialogComponent
  ]
})
export class CustomModule {}

暫無
暫無

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

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