首页 > 解决方案 > Angular:我需要“变更检测”方面的帮助

问题描述

我正在做一个有角度的项目,我需要掌握变更检测以使我的项目可用。

这是一个最小的复制:https ://stackblitz.com/edit/angular-3py5bh

<div *ngIf="timeleft$ | async as timeleft"> //countdown (rxjs)
    {{timeleft}}
</div>
<hello></hello> // simulated intensive function

所以,基本上,我有一个带有倒计时的主要组件,每 0.01 秒刷新一次。在这个组件中,我有一个嵌入的“hello”组件,其中包括(在实际项目中)非常密集的计算。我用“慢函数”模拟了这些密集的计算。

问题:每次倒计时刷新(所以100次/秒),Hello组件也被刷新,“慢函数”被调用......

结果倒计时显示坏了(太慢了)!!!

我知道答案依赖于“变化检测”,但我太新了,不能很好地处理它。这就是为什么我请求你的帮助!

非常感谢 !!!哔叽

标签: angularangular8angular2-changedetection

解决方案


我会尝试在您的“慢”组件上设置 changeDetection: ChangeDetectionStrategy.OnPush。这可以修复您的 stackblitz,如下所示:

import { ChangeDetectionStrategy, Component, Input} from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Result : {{mySlowFunction(8)}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent {
  @Input() name: string;

mySlowFunction(baseNumber) {
    let result = 0; 
    for (var i = Math.pow(baseNumber, 7); i >= 0; i--) {        
        result += Math.atan(i) * Math.tan(i) ;
    };
  return result;

}

}

推荐阅读