import { HttpClientModule } from "@angular/common/http"; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, inject, OnInit } from "@angular/core"; import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { FormBuilder, ReactiveFormsModule, Validators } from "@angular/forms"; import { Route, Router } from "@angular/router"; import { ButtonDirective, CfPermissionsService, CheckboxComponent, InputTextComponent } from "codefoxui"; import { LocalApiService } from "src/app/services/local.api.service"; import { UserService } from "src/app/services/user.service"; @Component({ standalone: true, selector: 'cf-login', changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: 'login.component.html', styleUrls: ['login.component.scss'], imports: [ HttpClientModule, ReactiveFormsModule, InputTextComponent, CheckboxComponent, ButtonDirective ] }) export class LoginComponent implements OnInit { cdr: ChangeDetectorRef = inject(ChangeDetectorRef); las: LocalApiService = inject(LocalApiService); fb: FormBuilder = inject(FormBuilder); destroyRef: DestroyRef = inject(DestroyRef); router: Router = inject(Router); userService: UserService = inject(UserService); permissionsService: CfPermissionsService = inject(CfPermissionsService); formGroup = this.fb.group({ username: this.fb.nonNullable.control('', [Validators.required]), password: this.fb.nonNullable.control('', [Validators.required]), stayLoggedIn: this.fb.nonNullable.control(false) }); loading: boolean = false; login(): void { if (this.loading) { return; } this.loading = true; this.formGroup.disable(); this.cdr.detectChanges(); this.las.login(this.formGroup.getRawValue()).pipe( takeUntilDestroyed(this.destroyRef) ).subscribe(({ userData }) => { this.userService.userData = userData; this.permissionsService.permissions = userData.permissions; this.router.navigate(['/']); }).add(() => { this.loading = false; this.formGroup.enable(); this.cdr.detectChanges(); }); } ngOnInit(): void { this.cdr.detectChanges(); } constructor() { this.cdr.detach(); this.formGroup.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.cdr.detectChanges(); }); } } export const LOGIN_ROUTE: Route = { path: 'login', component: LoginComponent, canActivate: [() => inject(UserService).userData === null ? true : inject(Router).createUrlTree(['/'])] }