错误: 使用 dialog.open 表单 angluer 服务时"找到组件工厂",即使它包含在 entryComponents 中



Proplem 描述

可注入服务调用dialog.open时,它失败并显示错误

错误


core.js:7187 ERROR Error: Uncaught (in promise): Error: No component factory found for LessonEndedDialogComponent. Did you add it to @NgModule.entryComponents?
Error: No component factory found for LessonEndedDialogComponent. Did you add it to @NgModule.entryComponents?

1. 对话框组件


@Component()
export class LessonEndedDialogComponent {}

2. 子模块


@NgModule({
declarations: [LessonEndedDialogComponent],
entryComponents: [LessonEndedDialogComponent],
})
export class CoursesModule { }

3. 根模块


@NgModule({
declarations: [AppComponent,],
bootstrap: [AppComponent]
})
export class AppModule { }

4. 根路由


const routes: Routes = [
{
path: 'courses',
loadChildren: () => import('./courses/courses.module').then(mod => mod.CoursesModule)
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

5. 注射服务


@Injectable({
providedIn: 'root'
})
export class NavigationService {
constructor(public dialog: MatDialog) {  }
displayDialog() {
this.dialog.open(LessonEndedDialogComponent);
}
}

解决方案 A

改变

providedIn: 'root'

providedIn: CoursesModule

Soution A ,失败

  • 沃林

检测到循环依赖关系:

  • 错误

初始化前无法访问"课程模块">

解决方案 B

贝斯

providedIn: 'root'

移动

entryComponents: [
LessonEndedDialogComponent
],

到根

AppModule

苏提翁B,作品

但课程结束对话组件是表单子模块

这将使模块依赖于子模块

女巫不利于模块的分离

手动导入可注射服务

步骤 1

改变

@Injectable({
providedIn: 'root'
})

@Injectable()

步骤 2

子模块上使用提供程序数组

@NgModule({
declarations: [LessonEndedDialogComponent],
entryComponents: [LessonEndedDialogComponent],
providers: [NavigationService],
})
export class CoursesModule { }

最新更新