使用 BsModalService 显示模态时出错

Error displaying modal using BsModalService

我正在尝试使用该服务显示模式并收到以下错误。我可以从按钮成功调用该服务,但从错误处理程序调用时出现此错误。

TypeError: Cannot read property 'attachView' of undefined
at ComponentLoader.webpackJsonp.../../../../ngx-bootstrap/component-loader/component-loader.class.js.ComponentLoader.show (vendor.bundle.js:19572)
at BsModalService.webpackJsonp.../../../../ngx-bootstrap/modal/bs-modal.service.js.BsModalService._showBackdrop (vendor.bundle.js:21508)
at BsModalService.webpackJsonp.../../../../ngx-bootstrap/modal/bs-modal.service.js.BsModalService.show

这是我的调用代码:

import { Injectable } from "@angular/core";
import { BsModalService, BsModalRef  } from "ngx-bootstrap/modal";
import { MessageBoxComponent } from "../message-box/message-box.component";

@Injectable()
export class NotificationService {
  private modalRef: BsModalRef;

  constructor(private modalService: BsModalService) {}

    showModal(type: string, title: string, message: any) {  
      this.modalRef = this.modalService.show(MessageBoxComponent);
      this.modalRef.content.type = type;
      this.modalRef.content.title = title;
      this.modalRef.content.message = message.toString();
    }
}

和应用程序模块:

import { NgModule } from '@angular/core';
import { ModalModule } from 'ngx-bootstrap/modal';

import { MessageBoxComponent } from './modules/common/message-box/message-box.component';

@NgModule({
  entryComponents: [MessageBoxComponent],
  imports: [ModalModule.forRoot()]
  //...etc
})
export class AppModule { }

谁能帮帮我?

将其添加到 MessageBoxComponent 的构造函数中

viewContainerRef:ViewContainerRef

参考 git 中心 issue#614

我想通了。我正在使用 Injector class 来解析我的 ErrorHandler 构造函数中的 BsModalService。似乎 ErrorHandler 是在 ApplicationRef 初始化之前创建的,这实际上是有道理的——所以它是未定义的。为了修复它,我只在抛出实际错误时解决了模态服务,即在 handleError() 方法内部。像这样:

export class CommonErrorHandler implements ErrorHandler {  
    private notification: NotificationService;

    constructor(private injector: Injector) { }

    handleError(error: any) {
        console.error(error);

        if (this.notification == null) {
            this.notification = this.injector.get(NotificationService, null);
        } 

        this.notification.showModal("danger", "Error", error);
    }
}