import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { MatCardModule } from '@angular/material/card'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { AuthService } from '../../services/auth.service'; import { EnterNavigationDirective } from 'base-core'; @Component({ selector: 'app-login', standalone: true, imports: [ CommonModule, ReactiveFormsModule, MatCardModule, MatFormFieldModule, MatInputModule, MatButtonModule, MatIconModule, MatProgressSpinnerModule, EnterNavigationDirective ], templateUrl: './login.component.html', styleUrl: './login.component.scss' }) export class LoginComponent implements OnInit, AfterViewInit { loginForm: FormGroup; isLoading = false; errorMessage = ''; hidePassword = true; @ViewChild('usernameInput') usernameInput!: ElementRef; constructor( private fb: FormBuilder, private authService: AuthService, private router: Router ) { this.loginForm = this.fb.group({ username: ['', [Validators.required]], password: ['', [Validators.required]] }); } ngOnInit(): void { if (this.authService.isAuthenticated()) { this.router.navigate(['/']); } } ngAfterViewInit(): void { setTimeout(() => { if (this.usernameInput?.nativeElement) { this.usernameInput.nativeElement.focus(); } }, 100); } onSubmit(): void { if (this.loginForm.invalid) { this.loginForm.markAllAsTouched(); return; } this.isLoading = true; this.errorMessage = ''; const { username, password } = this.loginForm.value; this.authService.login(username, password).subscribe({ next: (response) => { this.isLoading = false; if (response.success) { this.router.navigate(['/']); } else { this.errorMessage = response.message || response.error || '登录失败'; } }, error: (error) => { this.isLoading = false; this.errorMessage = error.message || '网络错误,请检查连接'; console.error('登录错误:', error); } }); } get username() { return this.loginForm.get('username'); } get password() { return this.loginForm.get('password'); } }