88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { HttpClient } from '@angular/common/http';
|
|
import {Component, signal} from '@angular/core';
|
|
import { Router } from '@angular/router';
|
|
import {ToastrService} from "ngx-toastr";
|
|
|
|
@Component({
|
|
selector: 'app-login',
|
|
templateUrl: './login.component.html',
|
|
styleUrls: ['./login.component.css'],
|
|
})
|
|
export class LoginComponent {
|
|
loginObj: any = {
|
|
"username": "",
|
|
"password": ""
|
|
};
|
|
errorMessage: string = '';
|
|
isLoading: boolean = false;
|
|
|
|
constructor(
|
|
private http: HttpClient,
|
|
private router: Router,
|
|
private toastService: ToastrService,
|
|
) { }
|
|
|
|
onLogin() {
|
|
this.errorMessage = '';
|
|
this.isLoading = true;
|
|
|
|
if (!this.loginObj.username || !this.loginObj.password) {
|
|
if (!this.loginObj.username) {
|
|
document.getElementById('username')?.classList.add('invalid');
|
|
} else {
|
|
document.getElementById('username')?.classList.remove('invalid');
|
|
}
|
|
|
|
if (!this.loginObj.password) {
|
|
document.getElementById('password')?.classList.add('invalid');
|
|
} else {
|
|
document.getElementById('password')?.classList.remove('invalid');
|
|
}
|
|
|
|
this.isLoading = false;
|
|
return;
|
|
}
|
|
|
|
this.http.post('http://127.0.0.1:8080/auth/login', this.loginObj).subscribe({
|
|
next: (res: any) => {
|
|
if (res.token) {
|
|
localStorage.setItem('loginToken', res.token);
|
|
localStorage.setItem('refreshToken', res.refreshToken);
|
|
localStorage.setItem('username', this.loginObj.username);
|
|
this.openSnackBar(false, 'Bienvenido ' + this.loginObj.username);
|
|
this.router.navigateByUrl('/dashboard');
|
|
}
|
|
this.isLoading = false;
|
|
},
|
|
error: (err) => {
|
|
this.isLoading = false;
|
|
this.openSnackBar(true, 'Error al iniciar sesion: ' + err.error.message);
|
|
}
|
|
});
|
|
}
|
|
|
|
hide = signal(true);
|
|
clickEvent(event: MouseEvent) {
|
|
event.preventDefault();
|
|
this.hide.set(!this.hide());
|
|
event.stopPropagation();
|
|
}
|
|
|
|
openSnackBar(isError: boolean, message: string) {
|
|
if (isError) {
|
|
this.toastService.error(message, 'Error');
|
|
} else
|
|
this.toastService.success(message, 'Éxito');
|
|
}
|
|
|
|
|
|
//SOLO PARA LA DEMO BORRAR EN PRODUCCION
|
|
redirectToUrl1() {
|
|
window.location.href = 'http://localhost:4201/auth/login';
|
|
}
|
|
|
|
redirectToUrl2() {
|
|
window.location.href = 'http://localhost:4200/auth/login';
|
|
}
|
|
}
|