一、Angular 生命钩子的执行顺序

https://angular.cn/guide/lifecycle-hooks#lifecycle-hooks

二、Angular 生命钩子、setTimeout、http请求等混合后的执行顺序

import { Component, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'my-test',
    templateUrl: './my-test.component.html'
})
export class MyTestComponent implements OnInit, OnChanges {
	constructor(private http: HttpClient) {}

    ngOnChanges(changes: SimpleChanges) {
        console.log('1 ngOnChanges');
    }

    ngOnInit() {
        console.log('2 ngOnInit');

        this.http
            .get(`${api}`)
            .pipe(
                finalize(() => {
                    console.log('8 Observable finalize');
                })
            )
            .subscribe(
                () => {
                    console.log('7 Observable subscribe');
                    setTimeout(() => {
                        console.log('9 Observable subscribe setTimeout');
                    }, 0);
                },
                err => {}
            );

        setTimeout(() => {
            console.log('5 ngOnInit setTimeout');
        }, 0);
    }

    ngAfterContentInit() {
        console.log('3 ngAfterContentInit');
    }

    ngAfterViewInit() {
        console.log('4 ngAfterViewInit');
        setTimeout(() => {
            console.log('6 ngAfterViewInit setTimeout');
        }, 0);
    }
}

在这里插入图片描述

更多推荐