Angular 中构造函数和 ngOnInit() 之间的逻辑混淆

Confusion about Logic between constructor and ngOnInit() in Angular

import { Component, OnInit } from '@angular/core';
import { OktaAuthService } from '@okta/okta-angular';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public title = 'my-project';
  public isAuthenticated: boolean;

  constructor(public oktaAuth: OktaAuthService) {
    this.oktaAuth.$authenticationState.subscribe(
      (isAuthenticated: boolean) => this.isAuthenticated = isAuthenticated
    );
  }

  async ngOnInit() {
    this.isAuthenticated = await this.oktaAuth.isAuthenticated();
  }

  login() {
    this.oktaAuth.loginRedirect();
  }

  logout() {
    this.oktaAuth.logout('/');
  }
}

我是新手Angular,当我看到这段代码时,我真的很困惑。我看了一些文章,我知道构造函数是初始化一个class,ngOnInit是在构造函数之后初始化运行。 但是在代码中,

Async/await 只是 thenables(或 Promises)的语法糖。

这使用 asyc/await:

async ngOnInit() {
  this.isAuthenticated = await this.oktaAuth.isAuthenticated();
}

这与上面没有 async/await 关键字的情况相同。

ngOnInit() {
  return this.oktaAuth.isAuthenticated().then(isAuth => this.isAuthenticated = isAuth);
}

上述两个示例 return 承诺,正如@GaurangDhorda 和@AluanHaddad 指出的那样,在等待承诺解决时可能会延迟组件的呈现。

您可以通过不从 ngOnInit 方法中 return 承诺来避免这种延迟,如本例所示:

ngOnInit() {
  this.oktaAuth.isAuthenticated().then(isAuth => this.isAuthenticated = isAuth);
}

关于构造函数与 ngOnInit 的问题,我会查看所有 Angular lifecycle event hooks.

的文档

ngOnInit

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

Called once, after the first ngOnChanges().

oktaAuth.isAuthenticated() 承诺被解决(在 ngOnInit 中)并且每当 OktaAuthService 通过 $authenticationState 可观察的(您已在构造函数中订阅)。