2017-03-15 57 views
1

我正在使用Angular 2.4.9並實現了一個自定義錯誤處理程序,它只捕獲所有錯誤並導航到錯誤路徑以顯示消息。使用自定義錯誤處理程序捕獲Javascript錯誤後Angular/Angular2數據綁定不工作

我有一個切換按鈕來顯示/隱藏綁定到一個布爾值的詳細消息(也嘗試了一個對象內的布爾值,即object.showError)如果我自己捕獲Http錯誤並拋出一個錯誤,所有工作正常。但是,如果我遇到諸如ViewWrappedError之類的Angular錯誤,數據綁定將拒絕工作。 (點擊)evets仍然有效,並且布爾值從true切換到false,其更改不會反映在頁面上。

我是否錯過了某些東西才能使之起作用?

import { Component } from '@angular/core'; 
import { ErrorService } from './error.service'; 
import { Error } from './index'; 

@Component({ 
    moduleId: module.id, 
    selector: 'error', 
    templateUrl: 'error.component.html', 
    styleUrls: ['error.component.css'] 
}) 

export class ErrorComponent { 

    public error: Error; 
    public showDetailedError: boolean; 

    constructor(private errorService: ErrorService) { 
    this.showDetailedError = false; 
    this.error = this.errorService.getError(); 
    } 
} 

HTML模板

<div class="error-container"> 
    <h1>Sorry, something went wrong.</h1> 
    <p class="error-message">An error occurred while processing your request. Details on this error can be found below.</p> 
</div> 
    <p *ngIf="!showDetailedError" (click)="showDetailedError = !showDetailedError" class="info-icon">Click for detailed description</p> 
</div> 

回答

0

你可以嘗試調用變化檢測:

@Injectable() 
class MyExceptionHandler implements ExceptionHandler { 
    constructor(private appRef:ApplicationRef) {} 
    call(error, stackTrace = null, reason = null) { 
    // do something with the exception 
    this.appRef.tick(); 
    } 
} 

當變化檢測期間發生異常時,角不會繼續變化探測的ErrorHandler處理後。 明確調用它可能會有所幫助。儘管我還沒有嘗試過。
我認爲在異常後繼續使用應用程序是不安全的。自定義錯誤處理程序主要是報告異常(例如在服務器日誌中)的方式,以便您可以在源代碼中修復原因。

另請參見Angular 2: Custom ExceptionHandler Change Detection Lag

+0

爲我工作。將ApplicationRef添加到我的組件中,並在切換我的詳細錯誤時手動觸發更改檢測 –

+0

感謝您的反饋 - 很好的瞭解。 –

0

它很難查明問題沒有任何代碼,但我認爲object.showError是最有可能您的問題。

角度變化檢測知道組件屬性,但不在複雜對象內部,尤其是當它存在於數組對象中時。嘗試將該標誌移出或使用getter函數進行綁定。

+0

目前,我的布爾值不在對象內部。我添加了一些代碼來釋放一些光 –