Good Morning,
Even after reading about the concepts and uses of async
and await
, i'm still having problems with real aplicattions of them.
Basically in my ngOnInit
I do a call to a function:
ngOnInit() {
this.authenticateUser();
}
Function that is:
authenticateUser() {
console.log("----Autenticando Usuário----");
this.token = localStorage.getItem("token");
this.userName = localStorage.getItem("userName");
this.userPhoto = localStorage.getItem("userPhoto");
this.currentUser = this.auth.getSession(this.token);
this.attributions = this.currentUser.sessao.grupos;
this.userEmail = this.currentUser.sessao.email;
this.instalation = this.currentUser.instalacao;
}
The problem is that currentUser
value returns as null
in its execution, because its value was setted before the return from the promise in this.auth.getSession(this.token);
This Auth
is constructed in a service called RestApiService
constructor(private auth: RestApiService) { }
Also I have inside that service the method getSession()
that returns a JSON
with user informations from the API
getSession(xtrToken) {
xtrToken = "{\"token\":\"" + xtrToken.toString() + "\"}";
this.http.post(this.apiURL + "/auth", xtrToken)
.subscribe(function (resposta) {
if (resposta != null) {
localStorage.setItem("currentUser", JSON.stringify(resposta));
if (window.location.href.indexOf("?") > -1) {
var url = window.location.href;
var value = url = url.slice(0, url.indexOf('?'));
value = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]', '');
var newUrl = value;
window.history.pushState({}, null, newUrl);
}
this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
}
});
return this.currentUser;
}
I've tried putting getSession
as async
, and in its call, something like this:
async authenticateUser() {
console.log("----Autenticando Usuário----");
this.token = localStorage.getItem("token");
this.userName = localStorage.getItem("userName");
this.userPhoto = localStorage.getItem("userPhoto");
this.currentUser = await this.auth.getSession(this.token);
this.attributions = this.currentUser.sessao.grupos;
this.userEmail = this.currentUser.sessao.email;
this.instalation = this.currentUser.instalacao;
}
But it didn't make any difference.
So, is there a way to wait the result from the API
before I set the value in this.currentUser
?