1 | import { Component, OnInit } from '@angular/core';
|
---|
2 | import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
|
---|
3 | import { DynamicDialogRef } from 'primeng/dynamicdialog';
|
---|
4 | import { LoginRequest } from 'src/app/_models/dto/loginRequest';
|
---|
5 | import { PlannerLocationDto } from 'src/app/_models/dto/plannerLocationDto';
|
---|
6 | import { UserDto } from 'src/app/_models/dto/userDto';
|
---|
7 | import { UsernameDto } from 'src/app/_models/dto/usernameDto';
|
---|
8 | import { UserService } from 'src/app/_services/user.service';
|
---|
9 |
|
---|
10 | @Component({
|
---|
11 | selector: 'app-login',
|
---|
12 | templateUrl: './login.component.html',
|
---|
13 | styleUrls: ['./login.component.css']
|
---|
14 | })
|
---|
15 | export class LoginComponent implements OnInit {
|
---|
16 |
|
---|
17 | form: FormGroup;
|
---|
18 | loginRequest: LoginRequest;
|
---|
19 | usernames: string[];
|
---|
20 |
|
---|
21 | constructor(private ref: DynamicDialogRef, private userService: UserService, formBuilder: FormBuilder) {
|
---|
22 | this.loginRequest = new LoginRequest();
|
---|
23 | this.usernames = [];
|
---|
24 |
|
---|
25 | this.form = formBuilder.group({
|
---|
26 | username: new FormControl('', [Validators.required]),
|
---|
27 | password: new FormControl('', [Validators.required, Validators.minLength(6)]),
|
---|
28 | },
|
---|
29 | {
|
---|
30 | validators: [
|
---|
31 | this.validateUser('username')
|
---|
32 | ]
|
---|
33 | }
|
---|
34 | );
|
---|
35 | }
|
---|
36 |
|
---|
37 | ngOnInit(): void {
|
---|
38 |
|
---|
39 | }
|
---|
40 |
|
---|
41 | onFormLogIn(loginRequest) {
|
---|
42 | const { valid } = this.form;
|
---|
43 | if (valid) {
|
---|
44 | this.ref.close(loginRequest);
|
---|
45 | }
|
---|
46 | }
|
---|
47 |
|
---|
48 | validateUser(username: string) {
|
---|
49 | return (formGroup: FormGroup) => {
|
---|
50 | const control = formGroup.controls[username];
|
---|
51 |
|
---|
52 | if (control.errors && !control.errors.validateUser) {
|
---|
53 | return;
|
---|
54 | }
|
---|
55 |
|
---|
56 | this.userService.getAllUsernames().subscribe(
|
---|
57 | data => {
|
---|
58 | this.usernames = data;
|
---|
59 | for (let i = 0; i < this.usernames.length; i++) {
|
---|
60 | if (control.value === this.usernames[i]) {
|
---|
61 | control.setErrors(null);
|
---|
62 |
|
---|
63 | break;
|
---|
64 | } else {
|
---|
65 | control.setErrors({ validateUser: true });
|
---|
66 | }
|
---|
67 |
|
---|
68 | }
|
---|
69 | }
|
---|
70 | );
|
---|
71 | return null;
|
---|
72 |
|
---|
73 | };
|
---|
74 |
|
---|
75 | }
|
---|
76 | }
|
---|