2017-08-11 60 views
2

我試圖顯示使用該服務的模態並獲取以下錯誤。我可以成功地從一個按鈕調用服務,但從錯誤處理程序調用時會出現此錯誤。使用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 { } 

誰能幫助我?

回答

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

添加到您的MessageBoxComponent

的構造
viewContainerRef:ViewContainerRef 

參考git的樞紐issue#614

+0

我以前試過,但它沒有工作,因爲它被注入爲空。我現在想出了我的問題,併發布了我如何修復它。不管怎麼說,還是要謝謝你 – Brendan