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是在构造函数之后运行。但是在代码中,
异步/等待只是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 lifecycle event hooks的文档。
ngOnInit
[Angular首先显示数据绑定属性并设置指令/组件的输入属性后,初始化指令/组件。
在第一个ngOnChanges()之后调用一次。
您的isAuthenticated
变量将在oktaAuth.isAuthenticated()
承诺被解析时(在ngOnInit
中)以及每当OktaAuthService
通过可观察到的$authenticationState
(您已在[构造函数)。