使用BsModalService显示模式时出错

时间:2017-08-11 07:37:37

标签: angular ngx-bootstrap

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

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

以及app模块:

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 { }

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

我弄明白了这个问题。我使用Injector类来解析我的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);
    }
}

答案 1 :(得分:0)

将其添加到MessageBoxComponent

的构造函数中
viewContainerRef:ViewContainerRef

参考git hub issue#614