|
| 1 | +import { Component } from '@angular/core'; |
| 2 | +import { ReactiveFormsModule , FormGroup, Validators, FormBuilder } from '@angular/forms'; |
| 3 | +import { Router, RouterLink } from '@angular/router'; |
| 4 | +import { AccountService } from './services/account.service'; |
| 5 | +import { CommonModule } from '@angular/common'; |
| 6 | + |
| 7 | +@Component({ |
| 8 | + selector: 'app-login', |
| 9 | + standalone: true, |
| 10 | + templateUrl: './login.component.html', |
| 11 | + styleUrls: ['./login.component.scss'], |
| 12 | + imports : [ |
| 13 | + CommonModule, |
| 14 | + ReactiveFormsModule, |
| 15 | + RouterLink, |
| 16 | + ] |
| 17 | +}) |
| 18 | +export class LoginComponent { |
| 19 | + loginForm: FormGroup; |
| 20 | + loading = false; |
| 21 | + errorMessage = ''; |
| 22 | + |
| 23 | + constructor( |
| 24 | + private fb: FormBuilder, |
| 25 | + private accountService: AccountService, |
| 26 | + private router: Router |
| 27 | + ) { |
| 28 | + this.loginForm = this.fb.group({ |
| 29 | + email: ['', [Validators.required, Validators.email]], |
| 30 | + password: ['', [Validators.required, Validators.minLength(6)]] |
| 31 | + }); |
| 32 | + } |
| 33 | + |
| 34 | + onSubmit() { |
| 35 | + if (this.loginForm.invalid) { |
| 36 | + this.loginForm.markAllAsTouched(); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + this.loading = true; |
| 41 | + this.errorMessage = ''; |
| 42 | + const { email, password } = this.loginForm.value; |
| 43 | + |
| 44 | + this.accountService.login(email, password).subscribe({ |
| 45 | + next: () => { |
| 46 | + this.loading = false; |
| 47 | + this.router.navigate(['/']); // redirige vers la page d'accueil |
| 48 | + }, |
| 49 | + error: (err) => { |
| 50 | + this.loading = false; |
| 51 | + this.errorMessage = err.error?.message || 'Erreur de connexion, vérifiez vos identifiants.'; |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + // Getters pour les erreurs |
| 57 | + get email() { return this.loginForm.get('email'); } |
| 58 | + get password() { return this.loginForm.get('password'); } |
| 59 | +} |
0 commit comments