0
Good afternoon, guys, next, I’m developing a project of my course with some people, but there’s an excerpt where I’m suffering a little for the reason that the code sends the request to my back (In Java) and already continues running the rest on time, It’s giving me trouble to do the verification I need... I am trying to do an existing login check, where of course there can be no two logins equal
export interface existeUsuario {
usuarioExistente: boolean;
}
verificaUsuarioExistente(login: string): boolean {
console.log(login); // Aparece no console o login digitado
var existe: boolean;
// Usando uma interface pois foi a única forma de conseguir puxar o back-end, se tiver algumas forma de usar somente um .get<boolean> me falem por favor
this.http.get<existeUsuario>(this.urlApi + 'verificaUser&login=' + login).subscribe(retorno => {
console.log(retorno); // Log: {usuarioExistente: true}
existe = retorno.usuarioExistente;
console.log('Retorno 1' + existe);
}
console.log('Retorno 2: ' + existe);
return existe;
}
cadastrarUsuario(login: string, senha: string, email: string) {
if(login!= '' && senha != '' && email != '') {
if(this.usuarioExistente(login) === true) {
console.log('Usuario já existe');
} else {
console.log('Usuario não existe');
}
} else {
console.log('Informações em Branco!');
}
}
As you can see, Return 2 is coming before Return 1, which ends up returning Undefined because it was not defined in . get yet, then it sets (always as true in momente because I put an existing login in my database)
Which Comeback 2?
– LeAndrade
Opa @Leandrade , I had forgotten to put in the code the number, but the Return 2 is only for testing the same variable, but instead of returning Undefined should be returning true also the first
– Matheus Ledra
NAY, should not, because the
console.log('Retorno 2: ' + existe);
is already processed as soon as the function is executed, and since the variable has no value it returnsundefined
!!– LeAndrade
@Leandrade is exactly right! I wanted to know in a way that this part was processed only after the variable had defined value, that is, after the . get get his answer
– Matheus Ledra
The return of a http is
assíncrono
, that is, it can return fast, delay or even not return, you will only get the return within the subscribe.– LeAndrade
Okay... and there’s no way I can get the code to wait for the answer to come, so I can make it mine
if(usuaroExistente == true)
?– Matheus Ledra
Man, if I was you, I wouldn’t do the job
verificaUsuarioExistente()
, would only make thecadastrarUsuario()
and there would validate if the user already exists!– LeAndrade
Hmm, and in that case would just put the . get inside the if condition?
– Matheus Ledra
That, exactly!
– LeAndrade