Update
您会看到它被称为乘法时间,因为 Angular 会在每个更改检测周期评估您在模板中使用的所有表达式。变更检测周期开始于ApplicationRef.tick https://github.com/angular/angular/blob/78146c1890b472621acf33d778477db8df816043/packages/core/src/application_ref.ts#L625 method.
当应用程序启动时calls https://github.com/angular/angular/blob/78146c1890b472621acf33d778477db8df816043/packages/core/src/application_ref.ts#L672立即使用该勾选方法,然后由以下人员管理ngZone.onMicrotaskEmpty https://github.com/angular/angular/blob/78146c1890b472621acf33d778477db8df816043/packages/core/src/application_ref.ts#L515订阅。
此外,每个勾选方法都会执行额外的检查检查无变化 https://github.com/angular/angular/blob/78146c1890b472621acf33d778477db8df816043/packages/core/src/application_ref.ts#L638对于开发模式。
所以你得到了
App starts
loadComponent
tick
checkChanges
evaluate getArray()
checkNoChanges
evaluate getArray()
ngZone.onMicrotaskEmpty
subscribe(all promised have been executed)
tick
checkChanges
evaluate getArray()
checkNoChanges
evaluate getArray()
...some time later
subscribe(you click somewhere)
tick
checkChanges
evaluate getArray()
checkNoChanges
evaluate getArray()
subscribe(you make a http request)
tick
checkChanges
evaluate getArray()
checkNoChanges
evaluate getArray()
之前的回答
您应该避免在 Angular 模板中使用执行复杂计算或执行副作用或在每次更改检测运行时返回新值的表达式。
特别是在你的代码中
<h1 *ngFor="let item of getArray()">
您将在每次模板检查时返回一个新数组。 ngForOf 指令检测到您更改了数组并尝试重新渲染它(如果您的项目是对象)。
如果您在代码中定义该数组一次,那就更好了。
arr = ['number one', 'number two']
<h1 *ngFor="let item of arr">
另一种适用于 ngForOf 指令的方法是使用 trackBy,但最好在 item 中拥有一些唯一的键。
See also
- https://angular.io/guide/template-syntax#no-visible-side-effects https://angular.io/guide/template-syntax#no-visible-side-effects
- 自定义元素上的 Angular 非常奇怪的错误 https://stackoverflow.com/questions/55677590/angular-very-weird-bug-on-a-custom-element/55678469#55678469