I am trying to create a CustomValidationService with a method that validates whether the userName is already in use. However, I encountered an error when attempting to add the userService, which resulted in the following message << Cannot read properties of undefined (reading 'userService') >>.
Below is my implementation of 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 implementation of userService:
@Injectable({
providedIn: 'root'
})
export class UserService {
public loggedIn = new BehaviorSubject<boolean>(false);
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)
}
}
The call to the CustomValidationService is made within the EmployeeDetailsComponent as shown below:
@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])
});
}
}