The Webby
The Webby

Reputation: 77

Angular 2 async validator

   isUnameTaken(formCtrl:FormControl): Promise<any>|Observable<any>{
    var status ;
    console.log(this.formGroup);

    this.http.post("http://localhost:3000/user/isAvaliable", { userName: formCtrl.value}).subscribe((resp:any)=>{
      console.log(resp);
       status = resp.status;
      console.log(status);
      if (status === 'success') {
        return Promise.resolve({ userExists: true });
      } else {
        return Promise.resolve(null);
      }
    });


  }

I am getting status as undefined because post request takes time to resolve I tried to work around using Promise.resolve to return promise so how to wait for the response in a proper way

Above function is angular validator function

Upvotes: 0

Views: 55

Answers (1)

user184994
user184994

Reputation: 18301

You can use the Observables map function to transform the value that's emitted by the Observable, like so:

import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

// ...

return this.http.post("http://localhost:3000/user/isAvaliable", { userName: formCtrl.value }).pipe(
  map((resp: any) => {
    console.log(resp);
    status = resp.status;
    console.log(status);
    return status === 'success' ? { userExists: true } : null;
  })
);

Upvotes: 1

Related Questions