2
Edit: solution in the third answer.
I’m trying to do a login function for a project on Ionic 2.
This function checks if the user is registered in the database through the php server and returns the user id if he has a registration.
My problem is that I eat the method http.get()
works asynchronously, I cannot check if the function return has been empty, since the return result is Undefined.
I tried it in two ways, using observable and Promise:
With Observable: function calling the service:
login()
{
this.usuario = this.loginservice.get_usuario(this.loginusuario).subscribe(response =>this.usuario = response);
console.log(this.usuario);
}
Service coding:
public get_usuario(usuario):Observable<any>
{
return this.http.get(this.urlusuario +"/"+ usuario.usuario +"/"+
usuario.senha);
}
Thus, the first time I click on the button that triggers the login() function, I receive 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);
}
service coding:
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 can return the id on the first execution of the login function, but I couldn’t find any way to access __zone_symbol__value which is where the object is stored according to the console.log()
.
I was wondering if there’s a way to wait for the response from http.get()
for the program to continue the execution (in case of using observable) or how do I access the object that is returned from the previous
.
Using the methods you posted, I was able to access the value of the file, but I started having the same error as Undefined when I triggered the login event the first time.
– Guilherme M
Ah... of course ... The.log console has to be inside the file, because it needs to wait for the answer to arrive in order to be able to access, and the only login it will expect is actually inside the . then ... The same could be done directly with subscribe, this.loginservice.get_usuario(this.loginusuario). subscribe(Response => { this.usuario = Response; console.log(this.usuario); }); , doing so.
– Lucas Brogni
Thank you so much for your help, it worked. =]
– Guilherme M
For nothing, we are there to help. D
– Lucas Brogni