首页 > 解决方案 > Angular中构造函数和ngOnInit()之间的逻辑混淆

问题描述

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 的新手,当我看到这段代码时,我真的很困惑。我读了一些文章,我知道构造函数是初始化一个类,ngOnInit 是在构造函数之后运行。但在代码中,

标签: javascriptangularokta

解决方案


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);
}

上述两个示例都返回了一个承诺,正如@GaurangDhorda 和@AluanHaddad 指出的那样,在等待承诺解决时,可能会延迟组件的渲染。

您可以通过不从您的方法返回一个承诺来避免这种延迟ngOnInit,就像在这个例子中一样:

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

至于您对构造函数与 . 的问题ngOnInit,我将查看所有Angular 生命周期事件挂钩的文档。

ngOnInit

在 Angular 首次显示数据绑定属性并设置指令/组件的输入属性后初始化指令/组件。

在第一个 ngOnChanges() 之后调用一次。

当promise 被解决(在 中)以及当通过 observable 省略一个新值时(你在构造函数中订阅了它),你的isAuthenticated变量将被改变。oktaAuth.isAuthenticated()ngOnInitOktaAuthService$authenticationState


推荐阅读