Check JSON Login Result with Angular 2x

Asked

Viewed 69 times

1

My service to enter has:

entrar(data: any): Observable<any> {
  console.log(data.email, data.senha);
  return this.http.get(`${this.baseUrl}/` + '?email=' + `${data.email}` + '&senha=' + `${data.senha}`);  
}

And my "login" component the login button has:

login() {
    this.jogadorService.entrar(this.user)
        .subscribe(() => {
            this.jogadorService.entrar(this.user);          
            alert('Login feito');
            //this.router.navigate(['/login'])
        });
  }

But it accepts any data. I wanted to check if user and password really exist and are equal. And if return the empty JSON {} then show message.

How can I do?

Taking advantage of the exposure, if the result is correct store in Localstorage the result.

1 answer

0


The second call to jogadorService is not doing anything, since it is not given a subscribe in it. Then you can remove it.

The function subscribe is the one that actually executes the call or executes the function, which in your case is an HTTP request. The result of the request is passed in the first callback, also called next(). The next receives a value that can be named in its own way, in your case this variable was dropped due to the use of the ().

Knowing this your request call, with the comparison of values received from the back-end should be as follows:

login() {
    this.jogadorService.entrar(this.user)
        .subscribe(resultado => {
            // ... logica de comparacao   
            resultado.login === "admin" // <~ exemplo

            alert('Login feito');
            this.router.navigate(['/login'])
        });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.