2016-06-13 42 views
3

我正试图在Angular 2应用程序中实现自定义ExceptionHandler,该应用程序向未定义的AlertsService提交未被捕获的错误。目标是允许主要App组件订阅AlertsService提供的警报,以便它可以在UI中显示错误。Angular 2:自定义ExceptionHandler更改检测延迟

我看到的问题是,直到遇到其他错误时,自定义ExceptionHandler提交给AlertsService的错误才会反映在UI中。这会导致UI永远只是AlertsService实际提供的内容之一。

我的猜测是,这种行为与变化检测和ExceptionHandler的特殊情况有关,但我不确定从哪里去。期待Angular2专家的帮助!下面

示例代码,普拉克在这里:https://plnkr.co/edit/xPoWCELA9IHqeLBS4wXs?p=preview

import { Component, ExceptionHandler, Injectable, OnInit, provide } from '@angular/core'; 
import { bootstrap } from '@angular/platform-browser-dynamic'; 
import { Subject } from 'rxjs/Subject' 

export interface Alert { 
    message: string; 
} 

@Injectable() 
export class AlertsService { 

    private alertTriggeredSubject = new Subject<Alert>(); 

    alertTriggered = this.alertTriggeredSubject.asObservable(); 

    triggerAlert(message: string) { 
    this.alertTriggeredSubject.next(<Alert>{ message: message }); 
    } 

} 

@Injectable() 
export class CustomExceptionHander { 

    constructor(private alertsService: AlertsService) { } 

    call(exception, stackTrace = null, reason = null) { 
    this.alertsService.triggerAlert(exception.originalException); 
    console.error('EXCEPTION:', exception); 
    } 
} 

@Component({ 
    selector: 'child-component', 
    template : ` 
    <h3>Child</h3> 
    <div id="child"> 
    <button (click)="breakMe()">Break Me!</button> 
    <div>Alerts Sent:</div> 
    <ul><li *ngFor="let error of errors">{{error}}</li></ul> 
    </div>` 
}) 
export class ChildComponent { 

    errors: string[] = []; 
    numErrors = 0 

    breakMe() { 
    this.numErrors++; 
    let error = `I broke it (${this.numErrors})`; 

    // The error added to the array below is never reflected in the 
    // "Alerts Sent:" <ul>...not sure why 
    this.errors.push(error); 
    console.info('ChildComponent.errors', this.errors); 

    // Simulate unhandled exception 
    throw new Error(error); 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template : ` 
    <h3>Parent</h3> 
    <div id="parent"> 
    <div>Alerts Received:</div> 
    <ul><li *ngFor="let alert of alerts">{{alert.message}}</li></ul> 
    <child-component></child-component> 
    </div>` 
    directives: [ChildComponent] 
}) 
export class App implements OnInit { 

    constructor(private alertsService: AlertsService) { } 

    alerts: Alert[] = []; 

    ngOnInit() { 
    this.alertsService.alertTriggered.subscribe(alert => { 
     this.alerts.push(alert); 

     // Alert gets received, but is not reflected in the UI 
     // until the next alert is received, even thought the 
     // alerts[] is up-to-date. 
     console.info('App alert received:', alert); 
     console.info('App.alerts:', this.alerts); 
    }); 
    } 
} 

bootstrap(App, [ 
    AlertsService, 
    provide(ExceptionHandler, { useClass: CustomExceptionHander }) 
]).catch(err => console.error(err)); 

回答

7

更新ExceptionHandler更名为ErrorHandlerhttps://stackoverflow.com/a/35239028/217408

orgiginal

变化检测是不是在年底运行的0处理程序抛出时发生的事件。

您可以手动调用变化检测,而是因为你需要一个ApplicationRef参考,并ApplicationRef取决于ExceptionHandler这使得一个整洁的周期和DI无法解决循环依赖,这变得有点复杂。

一种解决方法是代替ApplicationRef注入Injector并获取AplicationRef势在必行像

constructor(private alertsService: AlertsService, injector:Injector) { 
    setTimeout(() => this.appRef = injector.get(ApplicationRef)); 
} 

,然后在call调用变化检测等

call(exception, stackTrace = null, reason = null) { 
    this.alertsService.triggerAlert(exception.originalException); 
    this.appRef.tick(); 
    console.error('EXCEPTION:', exception); 
} 

Plunker example

+0

感谢您的快速响应。因此,如果我正确理解这一点,则更新异常处理程序以手动触发更改检测以处理因异常而未触发更改检测的情况?不完全直观,但它的作品。 – WayneC

+0

我想在异常之后做一个额外的更改检测周期是安全的。它不应该太频繁;-)可能有更好的方法。我不是自定义异常处理程序实现方面的专家。 –

+0

在我接受此标记之前,请遵循一个问题。另外,在按钮点击处理程序中,错误被推送到ChildComponent的错误[]。即使我们现在在ExceptionHandler中手动运行更改检测,该值也不会在UI中更新。任何想法为什么? – WayneC