6
respostas

Value = NULL

Gostaria de uma orientação/ajuda, fiz exatamente igual o professor, porém meu authToken não está recebendo o valor do token, está recebendo como NULL. obs: estou usando um API diferente, até o momento tudo está funcionando, somente isso que não deu certo.

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import {take, tap} from 'rxjs/operators';
import { Observable } from 'rxjs';

import { LoginUsuarioComponent } from 'src/app/home/signin/login-usuario.component';
import { UserComponent } from 'src/app/home/user.component';

  const API_URL = 'http://localhost:3000/usuario/login'
  const API = 'http://localhost:3000';


@Injectable({
  providedIn: 'root'
})



export class AuthService {


  constructor(private http: HttpClient) { }

  //LISTAR TODOS

  buscarTodos() {

    return this.http.get<UserComponent[]>(API + '/usuario/').pipe(tap(console.log));
  }



  /// LOGIN

  login(LoginUsuarioComponent: LoginUsuarioComponent): Observable<object>{
    return this.http.post(API + '/usuario/login', LoginUsuarioComponent, {observe: 'response'})  
    .pipe(tap(response => {const authToken: any = response['headers'].get('Authorization'); 
    window.localStorage.setItem('authToken', authToken);
    console.log(authToken);
    })).pipe(take(1));



} 

}

signin.component.ts

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core' 
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'
import { PlatformDetectorService } from 'src/app/core/platform-detector/platform-detector.service';

import { AuthService } from 'src/app/core/auth/auth.service';
import {LoginUsuarioComponent} from './login-usuario.component';


@Component({
    selector: 'tb-signin',
    templateUrl: './signin.component.html'

})
export class SignInComponent implements OnInit {
    @ViewChild('emailInput') userNameInput: ElementRef<HTMLInputElement> | undefined; 

     loginForm: any;

    constructor(private formBuilder:FormBuilder, private authService: AuthService,private PlatformDetectorService: PlatformDetectorService) { }

    ngOnInit(){

        this.createForm (new LoginUsuarioComponent()); 

    }

    createForm(LoginUsuarioComponent: LoginUsuarioComponent){

        this.loginForm = this.formBuilder.group({
            email: [LoginUsuarioComponent.email, Validators.compose([Validators.required, Validators.email])], // Passando paramentro de obrigatoriedade e desativando o botão submit enquanto o usuário não digitar o e-mail e senha 

            senha: [LoginUsuarioComponent.senha,Validators.required]


        })
    }
        onSubmit(){
        console.log ('Vai se autenticar');

        console.log(this.loginForm.value);

        if(this.loginForm.valid) {
            console.log ('submit');
            this.authService.login(this.loginForm.value).subscribe(
                success => console.log('sucesso'),
                error => console.error(error),
                () => console.log ('request completo')) 
            this.PlatformDetectorService.isPlatformBrowser() && // Usando o focus somente no navegador
            this.userNameInput?.nativeElement.focus();
            this.loginForm.reset(new LoginUsuarioComponent());

        }

    } 


}
6 respostas

Fala ai Gean, tudo bem? O que sua API está retornando nos cabeçalhos? Vi aqui que tu pega o cabeçalho Authorization:

response['headers'].get('Authorization')

Tente dar uma olhada no console (F12) do navegador na aba Network (Rede) e clicar na linha referente tal requisição.

Espero ter ajudado.

GENERAL
Request URL: http://localhost:3000/usuario/login
Request Method: POST
Status Code: 204 No Content
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin

RESPONSE HEADERS
Access-Control-Allow-Origin: *
Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwOTU5YWRhYTljZDFiYTdkZjIyYWNkYyIsImlhdCI6MTYyMTI1MzEyMSwiZXhwIjoxNjIxMjU2NzIxfQ.7Bwl62VF3b9yqjhWciMy-fdINVbv6E_W_cBQjs9SjIo
Connection: keep-alive
Date: Mon, 17 May 2021 12:05:21 GMT
Keep-Alive: timeout=5
X-Powered-By: Express
REQUEST HEADERS
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en,en-US;q=0.9,pt-BR;q=0.8,pt;q=0.7
Connection: keep-alive
Content-Length: 55
Content-Type: application/json
Host: localhost:3000
Origin: http://localhost:4200
Referer: http://localhost:4200/
sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36

REQUEST PAYLOAD
{email: "*********", senha: "123"} 
email: "***********"
senha: "123"

RESPONSE HEADERS

Access-Control-Allow-Origin: * Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwOTU5YWRhYTljZDFiYTdkZjIyYWNkYyIsImlhdCI6MTYyMTI1MzEyMSwiZXhwIjoxNjIxMjU2NzIxfQ.7Bwl62VF3b9yqjhWciMy-fdINVbv6E_W_cBQjs9SjIo Connection: keep-alive Date: Mon, 17 May 2021 12:05:21 GMT Keep-Alive: timeout=5 X-Powered-By: Express

como pode ver o token está sendo exibido na response headers, porém não consigo pegar ele, na requisição ele chega como null.

Fala ai Gean, tudo bem? Nesse caso adiciona um console.log para a gente ver como está o objeto response, algo assim:

login(LoginUsuarioComponent: LoginUsuarioComponent): Observable<object>{
    return this.http.post(API + '/usuario/login', LoginUsuarioComponent, {observe: 'response'})  
    .pipe(tap(response => {
    console.log(response)
    const authToken: any = response['headers'].get('Authorization'); 
    window.localStorage.setItem('authToken', authToken);
    console.log(authToken);
    })).pipe(take(1));
} 

Espero ter ajudado.

meu código:

  login(LoginUsuarioComponent: LoginUsuarioComponent): Observable<object>{
    return this.http.post(API + '/usuario/login', LoginUsuarioComponent, {observe: "response"})  
    .pipe(tap(response => { console.log(response)
    const token = response.headers.get('Authorization'); 
    this.UsuarioService.setToken('authToken');

    console.log(`usuário ${LoginUsuarioComponent.email} autenticado com token ${token}`);
    })).pipe(take(1)); 
  }

Console

HttpResponse {headers: HttpHeaders, status: 204, statusText: "No Content", url: "http://localhost:3000/usuario/login", ok: true, …}
body: null
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
ok: true
status: 204
statusText: "No Content"
type: 4
url: "http://localhost:3000/usuario/login"
__proto__: HttpResponseBase
clone: ƒ clone(update = {})
constructor: class HttpResponse
__proto__: Object

Fala Gean, loga o headers também, exemplo: console.log(response.headers).

Esqueci desse detalhe, desculpe.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software