[英]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('/');
}
}
我是 Angular 的新手,當我看到這段代碼時,我真的很困惑。 我讀了一些文章,我知道構造函數是初始化一個 class,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 生命周期事件掛鈎的文檔。
ngOnInit
Angular首先顯示數據綁定屬性並設置指令/組件的輸入屬性后初始化指令/組件。
在第一個 ngOnChanges() 之后調用一次。
當oktaAuth.isAuthenticated()
promise 被解析(在ngOnInit
中)以及OktaAuthService
通過$authenticationState
observable 省略一個新值時(您在構造函數中訂閱了該值),您的isAuthenticated
變量將發生突變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.