在Angular2,为什么有2次检查的setTimeout后的内容和观点? [英] In Angular2, why are there 2 times check for content and view after setTimeout?

查看:231
本文介绍了在Angular2,为什么有2次检查的setTimeout后的内容和观点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code

@Component({
  template: `<h1>Hello from A</h1>
  <ul>
    <li *ngFor="#letter of letters; #i = index">
      <button (click)="appendW(i)">{{letter | uppercase}}</button>
    </li>
  </ul>
  <button (click)="doSomething()">Click</button>`,
  pipes: [UpperCasePipe],
  directives: [NgFor]
})
export class AComponent {
  letters = ['a','b','c','d'];
  contructor(){

  }

  appendW(index) {
    // console.log(letter);
    setTimeout(()=>{
      this.letters[index] += "W";
    }, 1000)
  }
  ...
}

Plnkr

的setTimeout后,内容及观点两次角检查。有人能解释一下吗?为什么需要角度两次检查?

After setTimeout, angular checks twice for content and view. Can somebody explain this? Why does angular need to check TWICE?

推荐答案

角利用区要知道当一个事件完全通过修补一些异步API,如(的addEventHandler,setTimeout的,...)进行处理,然后每次运行后变化检测事件。

Angular utilizes zones to know when an event is fully processed by patching some async APIs like (addEventHandler, setTimeout, ...) and then runs change detection after each event.

在开发模式角度做一个额外的变化检测运行,只是第一个了。因为当时在两者之间任何情况下,没有变化应该发生。

In dev mode Angular does an additional change detection run, just after the first one. Because there was no event in between, no change should have happened.

如果模型仍改变,角认为这是一个可能的错误。

If the model still changed, Angular considers this to be a possible bug.

可能的原因:


  • 字段,getter或功能视图绑定到每一次,这被认为是改变返回不同的实例。结果
    这与返回数组的过滤功能子范围往往是。
    此子范围应该分配给一个字段,除非一个过滤标准已经改变返回相同的缓存实例。结果
    角仅pviously比较$ P $的身份和目前返回的数组,并忽略阵列(或其他对象)的内容是否仍然是相同的。

  • A field, getter or function the view binds to returns a different instance each time, which is recognized as change.
    This is often with functions that return a filtered subrange of an array. This subrange should be assigned to a field and return the same cached instance unless a filter criteria has changed.
    Angular only compares identity of the previously and currently returned array and ignores whether the content of the array (or other objects) is still the same.

code,它是由未在Angulars修补区注册引起的模型变化的事件调用。结果
这通常是由于未在角初始化fronm第三方库造成的。
无论是如果可能的话在角初始化它们,或通知有关角的变化(<一个href=\"http://stackoverflow.com/questions/34827334/triggering-angular2-change-detection-manually\">Triggering Angular2变化检测手动的)

Code that was invoked by an event that was not registered within Angulars patched zone caused a model change.
This is usually caused by 3rd-party libraries that aren't initialized fronm within Angular. Either initialize them within Angular if possible, or notify Angular about the change (Triggering Angular2 change detection manually)

在生产模式下只角检查一次,而忽略可能的副作用。

In production mode Angular just checks once and ignores possible side effects.

这篇关于在Angular2,为什么有2次检查的setTimeout后的内容和观点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆