Reputation: 159
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. I read some article, I know constructors is to initialize a class, ngOnInit is to run after constructor. But in the code,
Upvotes: 1
Views: 261
Reputation: 2818
Async/await is just syntactic sugar for thenables (or Promises).
This uses asyc/await:
async ngOnInit() {
this.isAuthenticated = await this.oktaAuth.isAuthenticated();
}
This does the same thing as above without the async/await keywords.
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.
You can avoid this delay by not returning a promise from your ngOnInit
method, like in this example:
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
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().
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).
Upvotes: 1