Ber*_* Ng 11 exception typescript angular
当Angular 2的异常处理程序捕获到异常时,UI不再"更新".我在这里有一个非常简单的例子:
https://plnkr.co/edit/iHDYpZ3fDlO6bhOtlTbQ
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按钮翻转布尔值,该布尔值反映在模板中的插值中.但是,一旦按下Break It按钮(这会抛出一个错误),当点击"Do it"按钮时,插值不再更新.但是,控制台仍会记录"正在进行"消息.
我正在处理的问题是我想创建一个自定义异常处理程序来警告用户,并且当出现问题时可能会做一些清除表单的工作,但我看到的是如果我在一个错误上抛出错误按钮单击以测试它,所有UI更新停止.但是,按钮继续起作用,这意味着如果表单处于良好状态,发布请求的任何按钮都会这样做.然而,UI已经停止更新并通知用户发生了什么.
我不确定这是否是区域或其他问题,但尝试NgZone.run()似乎并没有解决我的问题.如果错误意味着破坏组件的UI,那么我的问题的正确方法是什么?
自 angular 4.1.1 (2017-05-04) https://github.com/angular/angular/commit/07cef36
修复(核心):不要因为错误而停止变更检测
- 防止在出错时取消订阅区域
- 防止
EventEmitter在出错时取消订阅指令- 如果出现错误,防止在开发模式下分离视图
- 确保
ngOnInit只调用 1x(也在 prod 模式下)
它应该可以在没有额外代码的情况下工作
@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')
  }
}
在发生未处理的情况后,不要依赖代码执行Exception。您必须在您期望发生异常的地方处理异常。
错误处理: http://www.javascriptkit.com/javatutors/trycatch.shtml