import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { RouterLink } from '@angular/router'; import { MatButtonModule } from '@angular/material/button'; import { MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatIcon } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { AuthService } from 'src/app/services/auth.service'; import { TokenStorageService } from 'src/app/services/token-storage.service'; // Диалог входа: сам выполняет логин и закрывается только при успехе @Component({ selector: 'app-dialog', imports: [FormsModule, RouterLink, MatButtonModule, MatDialogModule, MatIcon, MatInputModule], changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './dialog.component.html', styleUrl: './dialog.component.scss' }) export class DialogComponent { private readonly dialogRef = inject(MatDialogRef); private readonly authService = inject(AuthService); private readonly tokenStorage = inject(TokenStorageService); username = ''; password = ''; readonly hidePassword = signal(true); readonly submitting = signal(false); readonly errorMessage = signal(''); togglePassword(event: MouseEvent): void { this.hidePassword.update(hide => !hide); event.stopPropagation(); } signIn(): void { this.submitting.set(true); this.errorMessage.set(''); this.authService.login(this.username, this.password).subscribe({ next: user => { this.tokenStorage.saveUser(user); this.dialogRef.close(true); // Перезагрузка нужна, чтобы шапка и страницы подхватили вошедшего пользователя window.location.reload(); }, error: err => { this.submitting.set(false); this.errorMessage.set(err.status === 401 ? 'Wrong username or password' : err.error?.message ?? 'Login failed, please try again'); } }); } }