简体   繁体   English

Angular - 服务注入

[英]Angular - Service injection

I am trying to add a service ( modal-dialog.service ) that should be instantiated when the application starts.我正在尝试添加一个应在应用程序启动时实例化的服务 ( modal-dialog.service )。 I added it to my general services folder with the providedIn: 'root' property.我使用providedIn: 'root'属性将它添加到我的常规服务文件夹中。 This service has to inject modal dialogs in the <body> tag, and has to accept a component type to be rendered in the modal dialog:该服务必须在<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;
}

The problem I'm facing is that, when I'm calling this injectDialogToBody method from a module passing it a component in that module so it is displayed inside the modal dialog, I get the error " No component factory found for XXXComponent. Did you add it to @NgModule.entryComponents? ".我面临的问题是,当我从一个模块中调用这个injectDialogToBody方法时,该方法将一个组件传递给该模块中的一个组件,因此它显示在模式对话框中,我收到错误“找不到 XXXComponent 的组件工厂。你有吗?将它添加到@NgModule.entryComponents? ”。

Moving this modal-dialog.service to a common module inside the modules folder and adding it to the providers of that module fixes the problem.将此modal-dialog.service移动到modules文件夹内的一个公共模块并将其添加到该模块的提供者中可以解决问题。 Why doesn't the service recognise the type of the component if placed inside the general services folder (outside the modules folder) and using the providedIn: 'root' ?如果放置在常规服务文件夹内(模块文件夹外)并使用providedIn: 'root'为什么服务不能识别组件的类型?

You have to add your DialogComponent in the entryComponents of the Module where it is declared.您必须将 DialogComponent 添加到声明它的模块的entryComponents中。

Following the Angular Documentation: https://angular.io/guide/dynamic-component-loader#dynamic-component-loader遵循 Angular 文档: https : //angular.io/guide/dynamic-component-loader#dynamic-component-loader

You have to do like this example: https://angular.io/guide/dynamic-component-loader#resolving-components你必须像这个例子一样: 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