【发布时间】:2019-11-21 06:00:50
【问题描述】:
当 Angular 加载视图并显示组件时,我正在尝试使用 performance.now() 获取时间戳。在官方文档中列出了一系列不同的可能性:
- ngOnChanges
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
见:https://angular.io/guide/lifecycle-hooks
我用ng new做了一个项目,非常简单,内容如下:
testing.component.html
<p>
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
</p>
app.component.html
<app-testing *ngFor="let i of Arr(num).fill(1)"></app-testing>
app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
Arr = Array; //Array type captured in a variable
num:number = 10000;
timeBefore : number = 0;
timeAfter : number = 0;
ngOnChanges(){
console.log('ngOnChanges');
}
ngOnInit(){
console.log('ngOnInit');
this.timeBefore = performance.now();
}
ngDoCheck(){
console.log('ngDoCheck');
}
ngAfterContentInit(){
console.log('ngAfterContentInit');
}
ngAfterContentChecked(){
console.log('ngAfterContentChecked');
}
ngAfterViewInit(){
console.log('ngAfterViewInit');
}
ngAfterViewChecked(){
console.log('ngAfterViewChecked');
this.timeAfter = performance.now();
console.log(this.timeAfter - this.timeBefore + " took miliseconds!");
}
}
我制作了一个视频来演示我的问题:
在视频中你可以看到我记录了所有的钩子,最后记录的是 ngAfterViewChecked。但是,当它被记录时,组件尚未显示。当组件实际显示给用户时,我需要运行一些代码(例如获取时间戳),以便我可以比较页面开始加载时的差异。
这可能吗?如果可以,我该怎么做?
【问题讨论】: