关于angular2更新时机的一些发现

来源:互联网 发布:canon mp259 清零软件 编辑:程序博客网 时间:2024/05/16 10:03

关于angular2更新时机的一些发现

引入:

angular2官网关于管道(Pipe)的介绍中说明,angular2的管道分为pure和impure。

  • 非纯管道Impure pipes

Angular会在每个组件的变更检测周期中执行非纯管道。 非纯管道可能会被调用很多次,和每个按键或每次鼠标移动一样频繁。

Angular executes an impure pipe during every component change detection cycle. An impure pipe will be called a lot, as often as every keystroke or mouse-move.

  • 纯管道Pure pipes

Angular只有在它检测到输入值发生了纯变更时才会执行纯管道。 纯变更是指对原始类型值(String、Number、Boolean、Symbol)的更改, 或者对对象引用(Date、Array、Function、Object)的更改。

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

Angular会忽略(复合)对象内部的更改。 如果我们更改了输入日期(Date)中的月份、往一个输入数组(Array)中添加新值或者更新了一个输入对象(Object)的属性,Angular都不会调用纯管道。

Angular ignores changes within (composite) objects. It won’t call a pure pipe if we change an input month, add to an input array, or update an input object property.

具体问题:

在以前的开发过程中,我们遇到过,一个双向绑定的数组,使用push或者splice函数时,画面并未发生刷新。目前看了正是由于类似的情况

解决方法:

第一种:

新建一个数组,重新赋值给双向绑定的变量,这样,相当于引用发生了变化,所以会更新模板。

第二种:

使用ngIf来切换模板文件中的代码段(可能是一个组件)。


第一种是方法性能应该更好。如果这种情况下,也有一个类似管道中pure的参数来设置就好了,目前还没发现其他方法。

0 0
原创粉丝点击