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是在构造函数之后运行。 但是在代码中,
答案 0 :(得分:1)
异步/等待只是 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
通过{{1}省略新值时,您的OktaAuthService
变量都会被突变。 }可观察到(您已在构造函数中订阅)。