I keep having the error:
**ERROR Error: NG01101: Expected async validator to return Promise or Observable.
Find more at https://angular.io/errors/NG01101**
This error URL does not exist. The error occurs in the call of the validator.
This is my code:
app.component.ts
import {Component} from '@angular/core';
import {FormBuilder,FormGroup,Validators} from '@angular/forms';
import {EmailValidator} from email.validator';
export class AppComponent{
form: FormGroup;
constructor(fb: FormBuilder) {
this.form = fb.group({
email: ['[email protected]', {asyncValidators:[EmailValidator(this.apiService)],updateOn: 'blur'}] //UPDATED with the help of Volodymyr Herchuk
});
}
}
email.validator.ts
import {AbstractControl, AsyncValidatorFn} from '@angular/forms';
import {ApiService} from '../services/api.service';
import {map} from 'rxjs';
export function EmailValidator(apiService:ApiService):AsyncValidatorFn{
return (control: AbstractControl)=>{
return apiService.validateEmail(control.value)
.pipe(
map(response=>{
return response.valid?response.valid:null;
})
);
};
}
api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class ApiService {
constructor(private http: HttpClient) {}
//returns {valid:true} or {valid:false}
public validateEmail(email: string){ // Observable
return this.http.get('/api/:email'.replace(':email', email)
);
}
}
I have been reading a lot examples, specially this video, which is a similar case, but i cannot find a solution. Can anyone tell me what i am missing? Thank you.
CodePudding user response:
Try EmailValidator()
so it will return validator function instead of just EmailValidator
I wanted to add it as a comment but I can't((