angular - Async Validator, where api returns a 404 in case of false. Angular4 -
import { component, oninit } '@angular/core'; import { formgroup, formcontrol, validators, formarray } '@angular/forms'; import { aservice } "app/a/services/a.service"; import { subscription } 'rxjs/subscription'; import { observable } "rxjs/rx"; @component({ selector: 'app-a', templateurl: './a.component.html', styleurls: ['./a.component.css']}) export class acomponent implements oninit { constructor(private aservice: aservice) {} ngoninit() { this.addeditaform = new formgroup({ 'name': new formcontrol(null, [validators.required],this.validatenameasyn) }); validatenameasync(control: formcontrol): promise<any> | observable<any> { return observable.timer(500).switchmap(() => { return this.aservice .nameexists(control.value) .map(result => (result ? { nameexists: true } : null)); }); }
aservice
nameexists(name: string) { let url = baseapiservice.urls.a + '/name=' + name; return this.http.get(url, this.baseapiservice.setoptions(this.userservice.userauthtoken())); }
this code, creating async validator validatenameasync reactive form control. haven't been able test whether works, because api returns 404 if name doesn't exists , object if does. question is, possible handle such response in case? if yes how? thanks
to have better control of async validator, don't use prescribed angular doc. write validator function takes value of control argument , not formcontrol. way can handle http request validates value other http request , use catch() operator handle 404.
take @ code sample have 2 async validators: first 1 uses formcontrol second (in ngoninit) doesn't. https://github.com/farata/angular2typescript/tree/master/angular4/form-samples/src/app/async-validator
i have added catch() operator there, , in case of 404, i'd have set validation error "can't validate ssn because of server issue".
Comments
Post a Comment