javascript - Angular中构造函数和ngOnInit()之间的逻辑混淆
问题描述
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);
}
上述两个示例都返回了一个承诺,正如@GaurangDhorda 和@AluanHaddad 指出的那样,在等待承诺解决时,可能会延迟组件的渲染。
您可以通过不从您的方法返回一个承诺来避免这种延迟ngOnInit
,就像在这个例子中一样:
ngOnInit() {
this.oktaAuth.isAuthenticated().then(isAuth => this.isAuthenticated = isAuth);
}
至于您对构造函数与 . 的问题ngOnInit
,我将查看所有Angular 生命周期事件挂钩的文档。
ngOnInit
在 Angular 首次显示数据绑定属性并设置指令/组件的输入属性后初始化指令/组件。
在第一个 ngOnChanges() 之后调用一次。
当promise 被解决(在 中)以及当通过 observable 省略一个新值时(你在构造函数中订阅了它),你的isAuthenticated
变量将被改变。oktaAuth.isAuthenticated()
ngOnInit
OktaAuthService
$authenticationState
推荐阅读
- java - 用Java检查和比较数据库中的数据(时间限制)的好方法是什么?
- sql - 如何将项目添加到 sqlite3 中的单个列表
- java - 如何使用 Netty 从 Java 应用程序提出 GET 查询?
- php - 给定 [API 基本 URL:] 的邮箱中的地址不符合 RFC 2822, 3.6.2。拉拉维尔
- mysql - 用其他列中的值替换列值
- javascript - 按钮不起作用,页面在 POST 方法后继续加载
- c# - 无法将类型“字符串”隐式转换为“System.Collections.Generic.List”
' - php - 如果从数据库中删除用户帐户但用户已登录,则销毁会话
- arduino - Arduino 的命令行参数(Teensy)
- c# - 没有从剃须刀页面发送 Http Put