[英]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('/');
}
}
I am new about Angular, when I saw this piece of code I am really confused.我是 Angular 的新手,当我看到这段代码时,我真的很困惑。 I read some article, I know constructors is to initialize a class, ngOnInit is to run after constructor.
我读了一些文章,我知道构造函数是初始化一个 class,ngOnInit 是在构造函数之后运行。 But in the code,
但在代码中,
Async/await is just syntactic sugar for thenables (or Promises). Async/await 只是thenables (或 Promises)的语法糖。
This uses asyc/await:这使用 asyc/await:
async ngOnInit() {
this.isAuthenticated = await this.oktaAuth.isAuthenticated();
}
This does the same thing as above without the async/await keywords.这与上面没有 async/await 关键字的情况相同。
ngOnInit() {
return this.oktaAuth.isAuthenticated().then(isAuth => this.isAuthenticated = isAuth);
}
Both of the above examples return a promise and, as @GaurangDhorda and @AluanHaddad pointed out, will likely delay the rendering of the component while waiting for the promise to resolve.上述两个示例都返回 promise,正如@GaurangDhorda 和@AluanHaddad 指出的那样,在等待 promise 解决时,可能会延迟组件的渲染。
You can avoid this delay by not returning a promise from your ngOnInit
method, like in this example:您可以通过不从
ngOnInit
方法返回 promise 来避免这种延迟,如下例所示:
ngOnInit() {
this.oktaAuth.isAuthenticated().then(isAuth => this.isAuthenticated = isAuth);
}
As for your questions about the constructor vs the ngOnInit
, I would take a look at the docs for all of the Angular lifecycle event hooks .至于您关于构造函数与
ngOnInit
的问题,我将查看所有Angular 生命周期事件挂钩的文档。
ngOnInit
ngOnInit
Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.
Angular首先显示数据绑定属性并设置指令/组件的输入属性后初始化指令/组件。
Called once, after the first ngOnChanges().
在第一个 ngOnChanges() 之后调用一次。
Your isAuthenticated
variable will be mutated when the oktaAuth.isAuthenticated()
promise is resolved (in the ngOnInit
) and whenever the OktaAuthService
omits a new value through the $authenticationState
observable (which you've subscribed to in the constructor).当
oktaAuth.isAuthenticated()
promise 被解析(在ngOnInit
中)以及OktaAuthService
通过$authenticationState
observable 省略一个新值时(您在构造函数中订阅了该值),您的isAuthenticated
变量将发生突变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.