NullInjectorError: No provider for NzModalRef!

原文链接:NullInjectorError: No provider for NzModalRef! – 每天进步一点点 (longkui.site)

0.背景

调试一个angular项目是出现了路由错误,报错没有找到这个路由。打开F12看报错信息,看到下面这些:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[TestComponent -> NzModalRef]:
StaticInjectorError(Platform: core)[TestComponent -> NzModalRef]:
NullInjectorError: No provider for NzModalRef!
Error: StaticInjectorError(AppModule)[TestComponent -> NzModalRef]:
StaticInjectorError(Platform: core)[TestComponent -> NzModalRef]:
NullInjectorError: No provider for NzModalRef!

1.原因及解决办法

NzModalRef 是一个动态产生模态框的组件,通过它可以动态的创建Modal。

上面的问题原因的出于下面的代码,

import { Component, OnInit } from '@angular/core';
import {NzModalRef } from "ng-zorro-antd";
@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.less']
})
export class TestComponent implements OnInit {

  constructor(
    editModal:NzModalRef
  ) { }

  ngOnInit() {
  }

}

解决办法1:

删除 NzModalRef 的导入和 construtor里面有关的内容

解决办法2:

上面editModal:NzModalRef 的部分不对,可以改成下面这样

  constructor(
 
  ) { }

   editModal:NzModalRef
  ngOnInit() {
  }

这样就正常了,不会报错了。

2.使用方法

正确使用NzModalRef的参考代码:

import {Component, OnInit, TemplateRef} from '@angular/core';
import {NzMessageService, NzModalRef, NzModalService} from "ng-zorro-antd";
@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.less']
})
export class TestComponent implements OnInit {

  constructor(
    private modalService: NzModalService,
    private message: NzMessageService,
  ) { }
  editModal:NzModalRef
  ngOnInit() {
  }

  openModal(title: TemplateRef<{}>, content: TemplateRef<{}>, footer: TemplateRef<{}>): void {
    this.editModal = this.modalService.create({
      nzTitle: title,
      nzContent: content,
      nzFooter: footer,
      nzWidth:1200,
      nzMaskClosable: false
    });
  }

}
 

posted on   longkui  阅读(106)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示