0

I am using the code below to catch errors in my small Angular 6 app... I am catching the errors, I am showing info in the console the problem is that the toasts do not show unless I click somewhere in the application, they don't show up all by themselves. I am using the ToastrService in other parts of the application and whenever I call it like I do it here it shows toats without having to click on anything.

Any idea what might be causing this behaviour?

import { Injectable, ErrorHandler, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { AppSettings } from '../../app.settings';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private injector: Injector) {}

  public handleError(error: any) {

    const router = this.injector.get(Router);
    const settings = this.injector.get(AppSettings)

    const toastr = this.injector.get(ToastrService);

    console.log(`Request URL: ${router.url}`);
    console.log(error);
    if (error instanceof HttpErrorResponse) {
      console.log("it is");
      if (error.status === 401) {
        router.navigate(['/login']);
        settings.settings.setLoadingSpinner(false);
        toastr.error('Logged in user no longer authenticated on server.', 'Unable to connect to server');
      } else if (error.status === 404) {
        console.log("it is 404");
        toastr.error('Unable to connect to server. Missing or wrong URL, please try again', 'Unable to connect to server');
        settings.settings.setLoadingSpinner(false);
      } else if (error.status === 0) {
        toastr.error('Server appears to be temporary unavailable', 'Unable to connect to server');
        settings.settings.setLoadingSpinner(false);
      } else if (error.status === 500) {
        toastr.error('Server appears to be temporary unavailable', 'Unable to connect to server');
        settings.settings.setLoadingSpinner(false);
      }

    } else {
      console.error(error);
      toastr.error('An error has occured', 'Sorry');

    }

  }

}

I have added the provider in the module also to use this class as error handler.

4

2 回答 2

1

请在构造函数中包含烤面包机服务并运行。根据我的理解,当服务被实例化时,烤面包机应该被启动。

于 2018-11-23T08:14:20.277 回答
0

我相信您可以导入并包含NgZone在您的构造函数中以按预期进行这项工作:

constructor(private injector: Injector, private zone: NgZone) {}

然后包装你的toastr电话:

this.zone.run(() => toastr.error('message', 'title'));
于 2020-07-03T18:44:39.620 回答