抛出异常后 Angular 2 不更新 View

标签 angular typescript exception

当 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 EventEmitters 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')
  }
}

Plunker Example

关于抛出异常后 Angular 2 不更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37836172/

相关文章:

html - 将 HTML 内容保存到数据库是个好主意吗?

angular - 如何将参数传递给 Angular 中的模态

angular - 没有路由的组件的延迟加载路由。 Angular 2

typescript Mocha : Module '"mocha "' has no exported member ' describe'. (2305)

c++ - 调用我的 CLR 项目时 KernelBase.dll 出现未处理的异常

c# - 使用 TryParse 设置对象属性值

angular - 如何在预提交时运行 ng lint 并检测错误?

javascript - 测试 eventEmiters 的最佳方式?

javascript - Firefox 无法创建使用 TypeScript 生成的类的实例

PHP PDO - 什么需要 try catch ?