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是在构造函数之后运行。 但是在代码中,
- 构造函数和 ngOnInit 之间的逻辑是什么?对于我的 理解,在构造函数中,它听取赋值 函数,并在构造后,通过分配初始化的类 oktaAuth.isAuthenticated()
- isAuthenticated 变量何时更改?
- 为什么我们需要异步 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);
}
上述两个示例都返回了一个 promise ,正如@GaurangDhorda 和@AluanHaddad 指出的那样,在等待 promise 解决时,可能会延迟组件的渲染。
您可以通过不从 ngOnInit
方法返回 promise 来避免这种延迟,如本例所示:
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()
promise 被解决(在 ngOnInit
中)并且每当 OktaAuthService
通过 $authenticationState
可观察对象(您已在构造函数中订阅)省略了一个新值。
关于javascript - 关于 Angular 中构造函数和 ngOnInit() 之间逻辑的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824953/