import { UsersService } from './../../../../shared/services/users.service'; import { User } from './../../../../shared/models/user.model'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { CreateFormUserAddAction, SaveUserFormAction, } from './../../../../ngrx/users/users.actions'; import { Store } from '@ngrx/store'; import { Component, OnInit } from '@angular/core'; import { MsgState } from 'src/app/ngrx/msg.state'; import { UserState } from 'src/app/ngrx/users/user.state'; @Component({ selector: 'app-user-create', templateUrl: './user-create.component.html', styleUrls: ['./user-create.component.css'], }) export class UserCreateComponent implements OnInit { userFormGroup!: FormGroup; constructor( private store: Store<{ userReducerKey: UserState }>, private fb: FormBuilder, private usersService: UsersService ) {} userState!: UserState; readonly msgState = MsgState; ngOnInit(): void { this.store.dispatch(new CreateFormUserAddAction({})); this.store.subscribe((myState) => { this.userState = myState.userReducerKey; this.userFormGroup = this.fb.group({ id: [0, Validators.required], firstname: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(15), ], ], lastname: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(15), ], ], email: ['', [Validators.required, Validators.email]], address: this.fb.group({ numRue: [0, [Validators.required, Validators.min(1)]], nomRue: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(25), ], ], bp: [0, [Validators.required, Validators.min(1)]], ville: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(15), ], ], pays: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(15), ], ], }), }); }); } onUserSave() { let user: User = this.userFormGroup.value; let lastname: string = user.lastname; this.usersService.getUserByName(lastname).subscribe((users: User[]) => { if (users.length > 0) { alert(lastname + ' ' + this.msgState.EXIST); return; } else{ if (window.confirm(MsgState.CONFIRM_ADD+' '+user.firstname+' '+user.lastname)) { this.store.dispatch(new SaveUserFormAction(user)); } } }); } onNewUser() { this.store.dispatch(new CreateFormUserAddAction({})); } tryEgain() { this.store.dispatch(new CreateFormUserAddAction({})); } }