Reputation: 124
I need to implement async validation with github api. I hope you help me.
export class UsernameValidator {
static usernameTaken(control: FormControl): Promise<ValidationResult> {
return new Promise((resolve, reject) => {
setTimeout(() => {
//How Can i use github Api like this:
// if (control.value === "this._http.get('http://api.github.com/users/'+this.username)")) {
if (control.value === "David") {
console.log('username taken')
resolve({"usernameTaken": true})
} else {
resolve(null);
};
}, 1000);
});
}
}
Thank you.
Upvotes: 4
Views: 1615
Reputation: 8335
This is implemented within a Reactive Form, but should be modifiable to a solution for the form driven method.
The validator is given the service that does the actual get via the API (a 404 is returned if a given user does not exist):
export function usernameTaken(httpService: HttpService) {
return control => new Promise((resolve, reject) => {
console.log("in validator");
//How Can i use github Api like this:
httpService.lookupUser(control.value).subscribe(data => {
console.log(data);
if(data.id) {
resolve({ usernameTaken : true})
} else {
resolve(null);
}
}, (err) => {
console.log("in error"+ err);
if(err !== "404 - Not Found") {
resolve({ usernameTaken : true});
} else {
resolve(null);
}
});
});
}
The service itself looks like this:
@Injectable()
export class HttpService {
constructor(private http: Http) {}
lookupUser(username: string): Observable<any> {
return this.http.get("https://api.github.com/users/" + username)
.map(this.extractData)
.catch(this.handleError) as Observable<any>;
};
<...>
}
And we inject in the service and apply the validator like so (third spot in the array is asyncValidators:
constructor(private fb: FormBuilder, private httpService: HttpService) {
this.name = 'Angular2',
this.form = this.fb.group({
username: ['', Validators.required, usernameTaken(this.httpService)]
});
With the actual input looking pretty normal:
<input type="text" placeholder="Username" formControlName="username"/>
Here's a Plunker demonstrating the usage of the async validator: http://plnkr.co/edit/19lp0E9x6L4kPyX0ORg0?p=preview
Upvotes: 6