Angular 2在抛出异常后不会更新视图

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));
Run Code Online (Sandbox Code Playgroud)

Do It按钮翻转布尔值,该布尔值反映在模板中的插值中.但是,一旦按下Break It按钮(这会抛出一个错误),当点击"Do it"按钮时,插值不再更新.但是,控制台仍会记录"正在进行"消息.

我正在处理的问题是我想创建一个自定义异常处理程序来警告用户,并且当出现问题时可能会做一些清除表单的工作,但我看到的是如果我在一个错误上抛出错误按钮单击以测试它,所有UI更新停止.但是,按钮继续起作用,这意味着如果表单处于良好状态,发布请求的任何按钮都会这样做.然而,UI已经停止更新并通知用户发生了什么.

我不确定这是否是区域或其他问题,但尝试NgZone.run()似乎并没有解决我的问题.如果错误意味着破坏组件的UI,那么我的问题的正确方法是什么?

yur*_*zui 5

自 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')
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例


And*_*ich 1

在发生未处理的情况后,不要依赖代码执行Exception。您必须在您期望发生异常的地方处理异常。

错误处理: http://www.javascriptkit.com/javatutors/trycatch.shtml

  • 这就是我过去一直做的事情,我同意例外是我的朋友。这里的问题是在生产中我们想要将错误发布到服务器并通知用户发生了一些不好的事情。如果 Angular 不再更新其视图,我就不能依赖 Angular 来做到这一点。我可能会在异常处理程序中回退到纯 JavaScript,但我也试图避免这种情况。 (5认同)