Angular Material 15自定义Alert弹窗报错:MatDialog无提供者
解决Angular Material 15自定义Alert弹窗的NullInjectorError问题
问题原因
你遇到的NullInjectorError: No provider for MatDialog!是因为CustomDialogService的注入范围与MatDialog的提供者所在范围不匹配:
- 如果你的
CustomDialogService使用providedIn: 'root',服务会在根注入器中实例化,但根模块(app.module.ts)未导入MatDialogModule,导致根注入器找不到MatDialog的提供者。 - 虽然你在
CustomDialogModule中导入了MatDialogModule,但如果服务不在该模块的注入器范围内,依然无法获取到MatDialog的实例。
解决步骤
1. 调整CustomDialogService的注入范围
将服务的providedIn从'root'改为CustomDialogModule,让服务在CustomDialogModule的注入器中实例化,该模块已导入MatDialogModule,自然能获取到MatDialog的提供者:
import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { CustomDialogComponent } from './custom-dialog.component'; @Injectable({ // 改为模块级注入 providedIn: CustomDialogModule }) export class CustomDialogService { constructor(private dialog: MatDialog) { } alert(message: string): void { this.dialog.open(CustomDialogComponent, { data: { message } }); } }
2. 确保CustomDialogModule的配置正确
确认CustomDialogModule中已导入MatDialogModule,并声明了弹窗组件:
import { NgModule } from '@angular/core'; import { MatDialogModule } from '@angular/material/dialog'; import { CustomDialogComponent } from './custom-dialog.component'; import { CustomDialogService } from './custom-dialog.service'; @NgModule({ imports: [MatDialogModule], declarations: [CustomDialogComponent], // 如果服务没有使用providedIn: CustomDialogModule,需要手动添加到providers // providers: [CustomDialogService], exports: [CustomDialogComponent] // 若外部需要直接使用组件,添加到exports }) export class CustomDialogModule { }
3. 在目标模块中导入CustomDialogModule
在需要使用弹窗的模块中导入CustomDialogModule即可,无需在根模块导入MatDialogModule:
import { NgModule } from '@angular/core'; import { CustomDialogModule } from '../custom-dialog/custom-dialog.module'; import { TargetComponent } from './target.component'; @NgModule({ imports: [CustomDialogModule], declarations: [TargetComponent] }) export class TargetModule { }
这样配置后,CustomDialogService会在CustomDialogModule的注入器中创建,依赖的MatDialog会从同一模块的注入器中获取,不会再出现提供者缺失的错误。
内容的提问来源于stack exchange,提问作者prashant kushwah
相关产品推荐
相关产品推荐

