Brendan
Brendan

Reputation: 41

Error displaying modal using BsModalService

I'm trying to display a modal using the service and get the following error. I can successfully call the service from a button but get this error when calling from an error handler.

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

Here is my calling code:

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

And the app module:

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

Can anyone help me?

Upvotes: 3

Views: 4362

Answers (2)

Brendan
Brendan

Reputation: 41

I figured out the problem. I was using the Injector class to resolve the BsModalService inside my ErrorHandler constructor. It seems the ErrorHandler is created before the ApplicationRef is initialised, which makes sense actually - so it was undefined. To fix it I only resolved the modal service when an actual error was thrown, i.e. inside the handleError() method. like so:

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

Upvotes: 1

Aravind
Aravind

Reputation: 41571

Add this to your constructor of MessageBoxComponent

viewContainerRef:ViewContainerRef

Refer git hub issue#614

Upvotes: 0

Related Questions