I have already researched numerous other SO questions, but none of the solutions worked for me.
My goal is to implement an async validator that checks if a entered username already exists. However, every time I type a letter into the input field, I encounter an error stating that my userService
instance is undefined
.
Here is my implementation of UserService
:
export interface UsernameCheck {
info: string,
usernameAvailable: boolean;
}
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'http://localhost:5001/project-f-angular/us-central1';
constructor(
private http: HttpClient
) { }
checkUsername(username: string) {
const params = new HttpParams().set('username', username);
return this.http.get<UsernameCheck>(`${this.apiUrl}/checkUsername`, {params});
}
}
The HTTP request is connected to a locally running Firebase Cloud Functions emulator.
Below is the component where I am utilizing it:
export class SignUpComponent implements OnInit {
signUpForm: FormGroup;
constructor(
private userService: UserService,
private formBuilder: FormBuilder) {
}
ngOnInit() {
this.signUpForm = this.formBuilder.group({
username: [null, Validators.required, this.existingUsername],
email: [null, [Validators.required, Validators.email]],
password: [null, Validators.required],
confirmPassword: [null, Validators.required]
});
}
existingUsername(control: FormControl): Promise<any> | Observable<any> {
console.log(control.value);
return this.userService.checkUsername(control.value)
.pipe(
map(res => {
return res.usernameAvailable ? null : {existingUsername: true};
})
);
}
}
Upon entering the first letter in the input field, I encountered the following error:
ERROR TypeError: Cannot read property 'userService' of undefined
at existingUsername (sign-up.component.ts:45)
at forms.js:1492
at Array.map (<anonymous>)
at _executeAsyncValidators (forms.js:1488)
at FormControl.asyncValidator (forms.js:1446)
at FormControl._runAsyncValidator (forms.js:4100)
at FormControl.updateValueAndValidity (forms.js:4053)
at FormControl.setValue (forms.js:4692)
at updateControl (forms.js:3299)
at DefaultValueAccessor.onChange (forms.js:3271)
In addition, I included my service in app.module.ts
under providers
.
If I subscribe to my userService
inside ngOnInit
, my method works as expected and returns the correct response.
As I am new to reactive forms and validators, I would appreciate any insights on what I might be doing wrong.