Edit: solution in the third answer.
I'm trying to do a login function for a project in Ionic 2.
This function checks if the user is registered in the database through the php server and returns the id of the user if he / she has a registration.
My problem is that since the http.get()
method works asynchronously, I can not check if the function return was empty, since the return result is set to undefined.
I tried two ways, using observable and promise:
With Observable: function that calls the service:
login()
{
this.usuario = this.loginservice.get_usuario(this.loginusuario).subscribe(response =>this.usuario = response);
console.log(this.usuario);
}
Service encoding:
public get_usuario(usuario):Observable<any>
{
return this.http.get(this.urlusuario +"/"+ usuario.usuario +"/"+
usuario.senha);
}
That way, the first time I click the button that triggers the login () function, I get the undefined value as a response. The second time I click, it returns the value of the previous request.
Using promise: Function calling the service:
login()
{
this.usuario = this.loginservice.get_usuario(this.loginusuario);
console.log(this.usuario);
}
encoding service:
public get_usuario(usuario):Promise<any>
{
var resultado;
return this.http.get(this.urlusuario +"/"+ usuario.usuario +"/"+ usuario.senha).toPromise().then(function(data){
return data;
});
}
Using promise I get the id return on the first execution of the login function, however I could not find any way to access the __zone_symbol__value which is where the object is stored according to console.log()
.
I want to know if there is a way to wait for the response of http.get()
to the program to continue execution (in case of using observable) or how do I access the object that is returned from the promise
.