0

我正在尝试ngx-toastr在我的全局错误处理程序中使用,但它给了我以下错误。

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)

我刚开始倾斜,所以我对此很陌生,不确定自己做错了什么。我查找了几种解决方案,但似乎都没有。

这是我的全局错误处理程序 -

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

这是我的 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
}

我尝试了几种解决方案,但似乎都没有奏效。我应该怎么办?

4

1 回答 1

1

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

}
于 2020-05-03T14:53:45.970 回答