Reputation: 304
I am trying to use ngx-toastr
in my global error handler, but it is giving me the following error.
Error: Cannot instantiate cyclic dependency! ApplicationRef
at throwCyclicDependencyError (core.js:8072)
at R3Injector.hydrate (core.js:17049)
at R3Injector.get (core.js:16803)
at injectInjectorOnly (core.js:940)
at ɵɵinject (core.js:950)
at Object.Overlay_Factory [as factory] (ngx-toastr.js:460)
at R3Injector.hydrate (core.js:17053)
at R3Injector.get (core.js:16803)
at injectInjectorOnly (core.js:940)
at ɵɵinject (core.js:950)
I kind of just started leaning angular, so I am new to this and not sure what I am doing wrong. I looked up several solutions but none of them seems to work.
Here's my global error handler -
import { ToastService } from './../services/toast.service';
import { ErrorHandler, NgZone, Injectable, Injector } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AppErrorHandler extends ErrorHandler {
constructor(private toast: ToastService,
private injector: Injector,
private zone: NgZone) {
super();
}
handleError(error) {
this.zone.run(() =>
this.toast.errorMsg(error, 'Title')
);
}
Here's my ToastService -
import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class ToastService {
constructor(private toastr:ToastrService) { }
errorMsg(msg, title) {
this.toastr.error(msg, title);
}
//Subsequently success, warning, and info
}
I tried several solutions, but none of them seems to be working. What should I do?
Upvotes: 0
Views: 1484
Reputation: 304
I found this on GitHub -
import { ErrorHandler, Injectable, Injector, Inject } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
/**
* Handle any errors thrown by Angular application
*/
@Injectable()
export class AppErrorHandler extends ErrorHandler {
constructor(
@Inject(Injector) private readonly injector: Injector
) {
super();
}
handleError(error) {
console.log("Handling error: " + error);
this.toastrService.error(error, 'Error!', { onActivateTick: true })
super.handleError(error);
}
/**
* Need to get ToastrService from injector rather than constructor injection to avoid cyclic dependency error
* @returns {}
*/
private get toastrService(): ToastrService {
return this.injector.get(ToastrService);
}
}
Upvotes: 2