发生这种情况是因为管道不纯净
纯管道:Angular 仅在检测到输入值发生纯变化时才执行纯管道。纯更改是对原始输入值(字符串、数字、布尔值、符号)的更改或更改的对象引用(日期、数组、函数、对象)。
不纯管道:Angular 在每个组件更改检测周期中执行不纯管道。不纯的管道经常被调用,就像每次击键或鼠标移动一样频繁。
来源:https://angular.io/guide/pipes
但是如果您出于任何原因确实需要管道不纯,出于性能考虑,您需要将组件更改检测策略设置为
OnPush
,并在应用更改时手动触发更改检测。
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'awesome-component',
templateUrl: './pda.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AwesomeComponent implements OnInit {
constructor(
private cd: ChangeDetectorRef,
) { }
...
fetchData() {
...
// after any data change
this.cd.markForCheck();
...
}
...
}