问题描述
这是我的Angular 4应用程序模块:
Here's my Angular 4 app module:
@NgModule({
declarations: [
AppComponent
],
providers: [
QuickBoardListService,
{provide: ErrorHandler, useClass: FrontExceptionHandler}
],
imports: [
BrowserModule,
CommonModule,
FormsModule,
HttpModule,
BrowserAnimationsModule,
NgbModule.forRoot(),
UpgradeModule,
// internal
BoardModule,
CoreModule,
DiscussModule,
FormModule,
SystemModule,
QuickBoardModule
],
bootstrap: [AppComponent]
如果在AppComponent中引发错误,则会调用
FrontExceptionHandler.handle在其他模块(如我的DiscussModule(在导入中)或该模块的任何导入)中触发的错误不会调用它.
FrontExceptionHandler.handle will get called if an error is thrown in AppComponentIt will not be called for error triggered in other modules such as my DiscussModule (in imports) or any of that module's imports.
我希望在所有模块中触发此ErrorHandler.我有很多模块,宁愿完全不提供此ErrorHandler.
I would like for this ErrorHandler to be triggered in all modules. I have a lot of modules, and would rather not provide this ErrorHandler in all.
我们正在从解决方案很简单的angular.js迁移出来:
We are migrating out of angular.js where the solution was simple:
$provide.decorator("$exceptionHandler", ['$delegate', '$injector',
function ($delegate, $injector) {
return function (exception, cause) {
$delegate(exception, cause);
在Angular 4中有没有办法做到这一点?
Is there a way to do this in Angular 4?
推荐答案
首先,让我们定义一个 GlobalErrorHandler 类,该类将从 ErrorHandler 继承,如下所示:
First, let's define a GlobalErrorHandler class that will inherit from ErrorHandler like so:
import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { LoggingService } from '../services'; //<-- Replace this with your logging service or something similar
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error) {
const loggingService = this.injector.get(LoggingService);
const message = error.message ? error.message : error.toString();
// log on the server
loggingService.log({ message });
});
throw error;
}
}
现在,您必须告诉Angular使用GlobalErrorHandler而不是默认的,将提供程序添加到 app.module.ts :
Now you have to tell Angular to use your GlobalErrorHandler instead of the default one adding the provider to your app.module.ts:
import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { GlobalErrorHandler } from './error-handler'; //<-- adapt the "from" to your file
import { ServicesModule } from './services';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
providers: [
{
provide: ErrorHandler,
useClass: GlobalErrorHandler
}
]
})
export class AppModule { }
这篇关于如何跨模块应用Angular ErrorHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!