Receive http client request status and login token at the angle

Asked

Viewed 1,488 times

0

My backend api returns a token and a status, I need to save the token to localstorage and redirect the user to the welcome screen if the status returned from the api is 200.

I tried something like:

usuario.modelts.:

export class Usuario{
    email: string;
    password: string;
}

login.componentts.:

 usuario: Usuario = new Usuario();

     fazerLogin(email: string, password: string): void{
        this.loading = true;
        this.authService.fazerLogin(email,password)

          .subscribe(

            (resp) => {
              console.log(resp);
            },

            (data) => {
                if(data == null){ //se o retorno da requisição for null, aciona a função que exibe o toast
                  this.toastUsuarioIncorreto();
                  this.authService.setUsuarioEstaAutenticado(false);
                  this.loading = false;
                }else{ //emite para o serviço que o usuário foi autenticado e que pode acessar as rotas do guard, redireciona para a home
                  this.authService.setUsuarioEstaAutenticado(true);
                  let token = JSON.stringify(data); //aqui é recebido o id do usuário
                  this.token = token; //aqui passa o valor do id do usuário para a variável do componente
                  localStorage.setItem('currentUser', this.token);
                  this.loading = false;
              }
            },
          );
        }

auth.service.ts:

  fazerLogin(email: string, password: string): Observable<HttpResponse<any>>  {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    return this._http.post<any>(AppSettings.API_ENDPOINT,
    {
      email: email,
      password: password
    },
    {
      headers: headers
    },


  )}

My console.log only returns the token, and I need the token and status to validate. Succor

1 answer

0


First, in your Auth.service.ts class, add the import:

import { map, catchError} from 'rxjs/operators';

After that, change your auth.service.ts

fazerLogin(email: string, password: string): Observable<HttpResponse<any>>  {

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    return this._http.post<any>(AppSettings.API_ENDPOINT,
               {email: email, password: password },
               { headers: headers, observe: 'response' })
          .pipe(
              map((response) => ({data: response.body, status: response.status}))
           );
    }

Change your method to the following...

usuario: Usuario = new Usuario();

 fazerLogin(email: string, password: string): void{
    this.loading = true;
    this.authService.fazerLogin(email,password).subscribe((response) => {
          // aqui você faz o seu processamento, acessando data e status do objeto declarado acima.

         let data = response.data;
         let statusCode = response.status;

         if(data == null){ //se o retorno da requisição for null, aciona a função que exibe o toast
              this.toastUsuarioIncorreto();
              this.authService.setUsuarioEstaAutenticado(false);
              this.loading = false;
            }else{ //emite para o serviço que o usuário foi autenticado e que pode acessar as rotas do guard, redireciona para a home
              this.authService.setUsuarioEstaAutenticado(true);
              let token = JSON.stringify(data); //aqui é recebido o id do usuário
              this.token = token; //aqui passa o valor do id do usuário para a variável do componente
              localStorage.setItem('currentUser', this.token);
              this.loading = false;
      })
    },
  );
}
  • With these changes I have: The property . map does not exist in type Observable<any>

  • I adjusted the answer, thank you for warning.

  • console.log(data) and console.log(statusCode); return Undefined

  • The type 'Observable<Httpevent<any>>' cannot be assigned to the type 'Observable<Httpresponse<any>>'. I also tried to change any to user, but without success

  • Ready Leticia, I changed again, where you pass the headers, add the observe property and change in the map method, the Sponse.json() for Sponse.body

Browser other questions tagged

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