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 { }