![](/img/trans.png)
[英]Why can't I use <template> as an angular2 component template?
[英]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.