angular - 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组件也被刷新,“慢函数”被调用......
结果倒计时显示坏了(太慢了)!!!
我知道答案依赖于“变化检测”,但我太新了,不能很好地处理它。这就是为什么我请求你的帮助!
非常感谢 !!!哔叽
解决方案
我会尝试在您的“慢”组件上设置 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;
}
}
推荐阅读
- node.js - json文件未显示在nodejs服务器中
- python - 如何通过记忆化使递归 fib 函数返回正确的值
- wordpress - 是否可以为 woocommerce 保存选定的过滤器?
- variables - While 循环执行的时间比预期的多 1 次
- scala - Scala 标准库中的 ArrayBuffer 实现可能效率低下
- ms-access - 如何修复此错误“错误 3001:无效参数”
- python - 仅打印列表中的 1 个值,但不止一个 | SQL LITE Python
- python - 如何安装并运行 selenium 依赖 chromedriver
- regex - 用于匹配两个数字之间的字符列表的正则表达式
- android - 我应该如何解码这个 json 响应?