3

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

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

谁能帮我?

4

2 回答 2

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);
    }
}
于 2017-08-21T00:49:22.273 回答
0

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

viewContainerRef:ViewContainerRef

参考 git hub问题#614

于 2017-08-18T19:44:29.377 回答