首页 > 解决方案 > 如何在 Angular 7 中获得正确的生命周期钩子

问题描述

当 Angular 加载视图并显示组件时,我正在尝试使用 performance.now() 获取时间戳。在官方文档中列出了一系列不同的可能性:

请参阅: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!");
  }
}

我制作了一个视频来演示我的问题:

https://youtu.be/xMk01kMwXl8

在视频中你可以看到我记录了所有的钩子,最后记录的是 ngAfterViewChecked。但是,当它被记录时,组件尚未显示。当组件实际显示给用户时,我需要运行一些代码(例如获取时间戳),以便我可以将差异与页面开始加载的时间进行比较。

这可能吗?如果可以,我该怎么做?

标签: angularlifecycle

解决方案


您看到的不是AppComponent尚未渲染,而是因为它的子组件仍在运行它们的生命周期钩子。

  • Angular 生成这些组件的方式被称为 单向,这意味着它完成生命周期钩子并从根组件开始一个接一个地更新整个组件树的 DOM 。

  • 在每个组件上,Angular 将运行与该组件关联的更改检测机制 ,并将确定该组件是否需要渲染/重新渲染,如果确实需要重新渲染,那么它将更新该组件的视图组件也会更新 DOM。

  • 这个过程是从组件树的根向下直到
    应用程序的叶子组件完成的

所以你看到的是AppComponent已经完成了它的生命周期钩子并被渲染,但它的子组件仍在运行它们。ngAfterViewInit() 是保证组件完成初始化为 View 后运行的方法。


推荐阅读