import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { HRMNotificationService } from './app.notification.service'; import { AuthService } from './_services/auth/auth.service'; import { ApiService } from './app.api.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-forgot-password', templateUrl: './forgot-password.component.html', styleUrls: ['./forgot-password.component.css'], changeDetection: ChangeDetectionStrategy.Eager, standalone: false, }) export class ForgotPasswordComponent implements OnInit { forgotPasswordForm: FormGroup; submitted = false; isSubmitting = false; // Set after the link is mailed: masked address + how long the link is valid sentToEmail: string = null; linkExpiryMinutes: number = null; constructor(public notificationService: HRMNotificationService, public authService: AuthService, public apiService: ApiService, public router: Router, private fb: FormBuilder) { } ngOnInit() { this.forgotPasswordForm = this.fb.group({ loginId: ['', Validators.required], }); } get f() { return this.forgotPasswordForm.controls; } showError(control: string): boolean { const c = this.forgotPasswordForm.get(control); return !!c && c.invalid && (this.submitted || c.touched); } onSubmit() { this.submitted = true; if (this.forgotPasswordForm.invalid || this.isSubmitting) { return; } const data = { loginID: (this.f['loginId'].value || '').trim() }; if (data.loginID === '') { this.f['loginId'].setValue(''); return; } this.isSubmitting = true; this.authService.forgotPassword(data).subscribe( (resp: any) => { this.isSubmitting = false; this.sentToEmail = resp?.maskedEmail; this.linkExpiryMinutes = resp?.expiryMinutes; this.notificationService.showSuccess('Password reset link has been sent to ' + this.sentToEmail); }, (err) => { this.isSubmitting = false; // 400 = account / email problem the user can act on -> warning; anything else is an error const message = (err && typeof err.error === 'string' && err.error) ? err.error : 'Could not send the password reset link. Please try again.'; if (err && err.status === 400) { this.notificationService.showWarning(message); } else { this.notificationService.showError(message); } } ); } onSendAgain() { this.sentToEmail = null; this.linkExpiryMinutes = null; this.submitted = false; } onGoBack() { this.backToLogin(); } // This component stays mounted (hidden) in app.main, so clear it before leaving private backToLogin() { this.submitted = false; this.isSubmitting = false; this.sentToEmail = null; this.linkExpiryMinutes = null; this.forgotPasswordForm.reset({ loginId: '' }); localStorage.removeItem('forgotpass'); this.router.navigate(['/login']); } }