Home > Back-end >  Add a service in Angular customValidationservice not working
Add a service in Angular customValidationservice not working

Time:03-28

I what to make a customvalidationService with a method that validates that the userName is not in use. However i need to include my userService to check that the user is not in use when I try to add the userService I get the following error << Cannot read properties of undefined (reading 'userService') >>

Here is my CustomValidationService

@Injectable({
  providedIn: 'root',
})
export class CustomValidationService {

  constructor(
    private userService: UserService
  ) { }
  userName(control: AbstractControl): { [Key: string]: any } | null {
    const userName: string = control.value;

    var employee: Employee = {
      //Some other fields ...
      "userName": userName
    }

    //This line is causing issue
   const userExists = this.userService.checkIfEmployeeUserNameExists(employee);

    if (!userExists) {
      return null;
    }
    else {
      return { 'userName': true };
    }
  }
}

Here is my userService

@Injectable({
  providedIn: 'root'
})
export class UserService {
  public loggedIn = new BehaviorSubject<boolean>(false); // {1}
  public employees: Employee[];

  baseUrl = environment.baseUrl;

  constructor(private fb: FormBuilder, private http: HttpClient) { }

      checkIfEmployeeUserNameExists(employee: Employee): Observable<boolean>  {
        return this.http.put<boolean>(this.baseUrl   'employees/isUserNameUnique', employee)
      }
   }

And here is where I make the call to the CustomValidationService in EmployeeDetailsComponent

@Component({
  selector: 'app-employee-details',
  templateUrl: './employee-details.component.html',
  styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {

  constructor(
    private http: HttpClient,
    public translate: TranslateService,
    private route: ActivatedRoute,
    private toastr: ToastrService,
    private userService: UserService,
    private typeService: UserTypeService,
    private menuService: MenuService,
    private _customValidation: CustomValidationService
  ) { }


  ngOnInit() {

    const customValidation = new CustomValidationService(this.userService);

      this.userService.getEmployee(this.employeeId).subscribe(async result => {
        this.employee = await result;
        this.employeeDetailForm = new FormGroup({
          userName: new FormControl(this.employee.userName, [Validators.required, customValidation.userName])
        });
}
}

CodePudding user response:

2 issues here

  1. the main reason you are seeing this is because you are passing a function without binding it. When you pass a function, 'this' is undefined. you have to bind it first

customValidation.userName.bind(customValidation)

this will get rid of the undefined error. However, ypur code will still not work as ypu think it will because...

  1. you are using async opepration as sync validator which will simply not work. you should use it as async validator in which case validator function returns Observable or Promjse that resolves to either null, or validation errors. This is similar to what you have now yet very different. Async validators are passed as 3rd argument of FormControl ctor
  • Related