簡體   English   中英

Angular2自定義ErrorHandler,為什么我可以登錄控制台但不能登錄模板?

[英]Angular2 custom ErrorHandler, why can I log to console but not to template?

我想在Angular2應用中遇到自定義錯誤。 因此,我在組件中擴展了ErrorHandler:

import { Component, ErrorHandler, OnInit } from '@angular/core';
import { GenericError } from './generic-error.component';

@Component({
    selector: 'custom-error-handler',
    templateUrl: 'app/error-handler/custom-error-handler.component.html?' + +new Date()
})

export class CustomErrorHandler extends ErrorHandler {
    errorText: string;

    constructor() {
        super(false);
    }

    ngOnInit() {
        this.errorText = 'Initial text!';
    }

    public handleError(error: any): void {
        if (error.originalError instanceof GenericError) {
            console.info('This is printed to console!');
            this.errorText = "I want it to print this in the template!";
        }
        else {
            super.handleError(error);
        }
    }
}

我的模板僅包含:

<span style="color:red">{{errorText}}</span>

首先,我看到“初始文本!” 在ngOnInit中設置的模板中。 符合預期。

然后,我可以從其他組件中拋出這樣的新異常:

throw new GenericError();

它使用handleError命中代碼,並打印到控制台,但不會使用以下命令更新我的模板errorText:

“我要它在模板中打印出來!”

就像在handleError函數中時,它忽略了我的模板。

這可能是什么問題?

*添加更多信息*

我認為我應該添加更多信息。 所以這是我為CustomErrorHandler制作的模塊(也許問題出在提供程序上?):

import { NgModule, ErrorHandler } from '@angular/core';
import { CommonModule } from '@angular/common';

import { CustomErrorHandler } from './custom-error-handler.component';

@NgModule({
    declarations: [
        CustomErrorHandler
    ],
    imports: [
        CommonModule
    ],
    exports: [
        CustomErrorHandler
    ],
    providers: [
        { provide: ErrorHandler, useClass: CustomErrorHandler }
    ]
})
export class CustomErrorModule { }

實際上只有CustomErrorHandler的一個實例(我使用Augury Chrome插件進行了檢查)。

為了完整起見,這是GenericError組件:

export class GenericError {
    toString() {
        return "Here is a generic error message";
    }
}

解決方案是按照問題的注釋軌道中的建議添加服務。 這樣,我可以在組件中設置屬性,並最終在模板中顯示它。

我創建了服務,因此它具有一個采用一個參數的函數。 注入服務,從component函數中的handleError調用服務的函數,然后將我想要的文本作為參數發送給模板。 然后,我使用一個可觀察的東西,將文本返回到組件。

在組件的構造函數中,我添加了該觀察器。

let whatever = this.cs.nameChange.subscribe((value) => {
  setTimeout(() => this.errorText = value);
});

我需要添加setTimeout,否則它將在第二次更改可觀察對象之前不會更新模板。

唷! Angular團隊應該在將來的版本中簡化此全局異常處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM