简体   繁体   English

Angular2自定义ErrorHandler,为什么我可以登录控制台但不能登录模板?

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

I would like to have custom errors in my Angular2 app. 我想在Angular2应用中遇到自定义错误。 Thus I have extended ErrorHandler in my component: 因此,我在组件中扩展了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);
        }
    }
}

My template simply contains: 我的模板仅包含:

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

First I see "Initial text!" 首先,我看到“初始文本!” in the template as set in ngOnInit. 在ngOnInit中设置的模板中。 That's as expected. 符合预期。

I can then throw a new exception like this from a different component: 然后,我可以从其他组件中抛出这样的新异常:

throw new GenericError();

and it hits the code with handleError and prints to console but it doesn't update my template errorText with: 它使用handleError命中代码,并打印到控制台,但不会使用以下命令更新我的模板errorText:

"I want it to print this in the template!" “我要它在模板中打印出来!”

It's like it ignores my template, when inside the handleError function. 就像在handleError函数中时,它忽略了我的模板。

What could be the problem here? 这可能是什么问题?

* ADDED MORE INFORMATION * *添加更多信息*

I thought I should add some more information. 我认为我应该添加更多信息。 So here is the module I made for CustomErrorHandler (maybe the problem is with the providers?): 所以这是我为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 { }

There is indeed only one instance of the CustomErrorHandler (I checked with the Augury Chrome plugin). 实际上只有CustomErrorHandler的一个实例(我使用Augury Chrome插件进行了检查)。

For completeness, here is is the GenericError component: 为了完整起见,这是GenericError组件:

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

The solution was to add a service as suggested in the question's comment track. 解决方案是按照问题的注释轨道中的建议添加服务。 This way I can set the property in the component and eventually show it in the template. 这样,我可以在组件中设置属性,并最终在模板中显示它。

I created the service, so that it has a function which takes one parameter. 我创建了服务,因此它具有一个采用一个参数的函数。 Injected the service, call the service's function from the handleError in the component function, and send the text I want in the template as the parameter. 注入服务,从component函数中的handleError调用服务的函数,然后将我想要的文本作为参数发送给模板。 Then I use an observable, to get the text back to the component. 然后,我使用一个可观察的东西,将文本返回到组件。

In the constructor of the component, I added this observer. 在组件的构造函数中,我添加了该观察器。

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

I needed to add the setTimeout, or else it would not update the template before the second time the observable was changed. 我需要添加setTimeout,否则它将在第二次更改可观察对象之前不会更新模板。

Phew! 唷! The Angular team should make this global exception handling easier in future releases. Angular团队应该在将来的版本中简化此全局异常处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM