Angular2-Toaster: When used in ErrorHandler the toaster doesn't show

When I use the toaster service inside a class that implements ErrorHandler then the toaster doesn’t show.

Now if the error is originating from within Angular 2 then the toaster will show but if I am using atob function inside a component and atob throws an error then the toaster doesn’t show and no error will be thrown either, so I can inject the service and I can call it but no toaster is shown

@Injectable()
export class GlobalErrorHandlerService implements ErrorHandler {
    constructor(private injector: Injector) {
    }

    handleError(error) {
        const logger = this.injector.get(AppLoggerService);       
        logger.error(`Unexpected error`);
    }
}

and thats my AppLoggerService

import {Injectable} from '@angular/core';
import {ToasterService} from 'angular2-toaster';

@Injectable()
export class AppLoggerService {
    constructor(private toasterService: ToasterService) {

    }

    public info(message: string) {
        this.toasterService.pop({
            type: 'success',
            title: '',
            body: message,
            showCloseButton: false
        });
    }

    public error(message: string) {
        this.toasterService.pop({
            type: 'error',
            title: '',
            body: message,
            showCloseButton: false
        });
    }
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

@Stabzs

If you update the my-error-handler.ts file to the following, then you can get the toast to show. I guess this is good enough for me for now, actually. But if you want to play around with the code, maybe you can work out what’s happening (but it’s definitely related to change detection and error handling).

my-error-handler.ts

import { ErrorHandler, Injectable, Injector, ApplicationRef} from '@angular/core';
import { ToasterService } from 'angular2-toaster';

@Injectable()

export class MyErrorHandler extends ErrorHandler {

    constructor(private injector: Injector) {

        super(false);
    }

    public handleError(error: any): void {

        let toasterService = this.injector.get(ToasterService);
        let appRef = this.injector.get(ApplicationRef); 

        console.log("Error thrown:");
        console.log(error);
        toasterService.pop('error', error, error);
        appRef.tick();
    }
}

You can fork this plunker http://embed.plnkr.co/1POpuc1tDpxK7dw1BD5d/ which is running 4.0.0.