我为所有未处理的异常在 Angular(版本 5.2.0)中实现了一个全局错误处理程序。
全局错误处理程序如下所示:
import { Router } from '@angular/router';
import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { LoggingService } from '../services/logging.service';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private router: Router;
constructor(injector: Injector, private zone: NgZone, private loggingService: LoggingService) {
setTimeout(() => {
this.router = injector.get(Router);
});
}
handleError(error) {
this.loggingService.logErrorToApi(error);
this.zone.run(() => this.router.navigate(['/error']));
}
}
路由仅在我有电话时才有效this.zone.run(...)
。如果我删除此调用,则路由只会将路由添加error
到 URL 而不会显示组件。ngOnInit 也没有被调用。
如果我必须使用这样的“hack”来让我的路由对我有用,那么我的应用程序中的某个地方似乎配置错误。
有人知道我需要改变什么才能让它在没有区域调用的情况下运行吗?
我的路由:
const appRoutes: Routes = [
{
path: 'error',
component: ErrorComponent
},
{
path: '',
component: HomeComponent,
canActivate: [CookieGuard]
},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
HomeComponent,
PageNotFoundComponent,
ErrorComponent
],
imports: [
RouterModule.forRoot(appRoutes, { enableTracing: !environment.production }),
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
HttpClientXsrfModule,
],
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
ApiHttpClientService,
AppSettingsService,
CookieGuard,
LoggingService
],
bootstrap: [AppComponent]
})
export class AppModule { }
这是我调用的错误组件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'error',
templateUrl: './error.component.html',
styleUrls: ['./error.component.scss']
})
export class ErrorComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}