You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular打开MatDialog时出现NullInjectorError: No provider for _0!报错问询

问题根源

报错是因为MaintainWorkGroupComponent的构造函数包含非注入类型参数WorkGroup,Angular依赖注入系统找不到对应提供者导致的,生产打包后变量名被混淆为_0,所以报错信息辨识度低。


修复步骤

1. 修正app.module.ts配置

组件不需要声明为提供者,删除providers数组中的所有组件类:

// 修正后的providers配置
providers: [
  Session // 仅保留服务类
],

若你使用Angular 9及以上版本,entryComponents配置可以直接删除,MatDialog组件不需要额外声明为入口组件。

2. 修正弹窗组件MaintainWorkGroupComponent的传参逻辑

自定义参数通过MatDialog的MAT_DIALOG_DATA注入,构造函数仅保留可注入的服务类:

import { Component, OnInit, Inject } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

// 其余导入不变

export class MaintainWorkGroupComponent implements OnInit {
  public workGroup!: WorkGroup;
  private operationType: string = constants.COMPONENT.MAINTAIN.OPERATION_TYPE.POST;

  constructor(
    private session: Session, 
    public thisDialogRef: MatDialogRef<MaintainWorkGroupComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {workGroup?: WorkGroup}
  ) {
    if (!data?.workGroup) 
      this.workGroup = new WorkGroup("", "");
    else {
      this.workGroup = {...data.workGroup};
      this.operationType = constants.COMPONENT.MAINTAIN.OPERATION_TYPE.PUT;
    }
  }

  // 其余代码不变,注意修正onSubmit中的判断符号
  public onSubmit(form: NgForm): void {
    // 原代码的=是赋值操作,改为===做相等判断
    if (this.operationType === constants.COMPONENT.MAINTAIN.OPERATION_TYPE.POST)
      this.session.apiManager.WorkGroupApi.createWorkGroup(this.workGroup);
    else
      this.session.apiManager.WorkGroupApi.updateWorkGroup(this.workGroup);

    this.thisDialogRef.close();
  }
}

3. 修正触发组件ItemWorkGroupComponent的弹窗调用逻辑

删除手动创建组件实例的错误代码,通过open方法的data参数传递自定义数据:

export class ItemWorkGroupComponent implements OnInit {
  @Input() workGroup!: WorkGroup;

  constructor(private session: Session, private matDialog: MatDialog) { }

  ngOnInit(): void {
  }

  public openMaintainDialog() {
    const dialogRef = this.matDialog.open(MaintainWorkGroupComponent, {
      autoFocus: true,
      closeOnNavigation: true,
      data: {
        workGroup: this.workGroup
      }
    });

    dialogRef.afterClosed().subscribe(result => {
      // 弹窗关闭后的后续逻辑,比如刷新列表
    });
  }
}

内容的提问来源于stack exchange,提问作者liegolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:45:04