【问题标题】:Angular 2 Toastr Not Working in Global Error HandlerAngular 2 Toastr 在全局错误处理程序中不起作用
【发布时间】:2020-05-03 14:19:34
【问题描述】:

我试图在我的全局错误处理程序中使用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
}

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

【问题讨论】:

标签: angular angular-errorhandler ngx-toastr


【解决方案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);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2013-03-06
    • 2023-04-04
    相关资源
    最近更新 更多