当 Angular 2 的异常处理程序捕获异常时,UI 不再“更新”。
我有一个非常简单的例子here :
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;
}
@Component({
selector: 'my-app',
template : `
<h3>Parent</h3>
{{aValue}}
<br/>
<br/>
<button (click)='doIt()'>do it</button>
<br/>
<br/>
<button (click)='breakIt()'>break it</button>
`
})
export class App implements OnInit {
private aValue: boolean = true
constructor() { }
alerts: Alert[] = [];
doIt(){
console.log('Doing It')
this.aValue = !this.aValue
}
breakIt(){
console.log('Breaking It')
throw new Error('some error')
}
}
bootstrap(App).catch(err => console.error(err));
Do It 按钮翻转 boolean
,这反射(reflect)在模板的内插值中。但是,一旦按下 Break It
按钮(这会引发错误),当按下“Do it”按钮时,内插值将不再更新。但是,控制台仍会记录消息 Doing it
。
我正在处理的问题是我想创建一个自定义异常处理程序来警告用户,并可能在出现问题时做一些工作来清除表单,但我看到的是如果我抛出一个单击按钮进行测试时出错,所有 UI 更新都会停止。然而,按钮继续发挥作用,这意味着如果表单处于良好状态,任何发布请求的按钮都会这样做。然而,UI 已停止更新并通知用户发生了什么。
我不确定这是区域问题还是其他问题,但尝试 NgZone.run()
似乎并没有解决我的问题。如果错误旨在破坏组件的 UI,那么解决我的问题的正确方法是什么?
最佳答案
自 Angular 4.1.1 (2017-05-04) https://github.com/angular/angular/commit/07cef36
fix(core): don’t stop change detection because of errors
- prevents unsubscribing from the zone on error
- prevents unsubscribing from directive
EventEmitter
s on error- prevents detaching views in dev mode if there on error
- ensures that
ngOnInit
is only called 1x (also in prod mode)
它应该可以在没有额外代码的情况下工作
@Component({
selector: 'my-app',
template : `
{{aValue}}
<button (click)='doIt()'>do it</button>
<button (click)='breakIt()'>break it</button>
`
})
export class App implements OnInit {
private aValue: boolean = true
doIt(){
console.log('Doing It')
this.aValue = !this.aValue
}
breakIt(){
console.log('Breaking It')
throw new Error('some error')
}
}
关于抛出异常后 Angular 2 不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37836172/