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());
}
}
}