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
    });
  }

}