| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- 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<HTMLInputElement>;
-
- 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');
- }
- }
|