Skip to content

Instantly share code, notes, and snippets.

@0x14Rp
Forked from nicobytes/66-async-validations.md
Created April 29, 2020 21:52
Show Gist options
  • Save 0x14Rp/921ada048d8f60a9c9c2d6bb5bea0bc3 to your computer and use it in GitHub Desktop.
Save 0x14Rp/921ada048d8f60a9c9c2d6bb5bea0bc3 to your computer and use it in GitHub Desktop.

service

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor(
    private http: HttpClient
  ) { }

  checkEmail(email: string) {
    // simulate http.get()
    return of({ isEmailAvailable: email !== 'nicolas@gmail.com'})
      .pipe(delay(500));
  }
}

validations

static validateEmail(userService: UserService) {
    return (control: AbstractControl) => {
      const value = control.value;
      return userService.checkEmail(value)
      .pipe(
        map(response => {
          const isEmailAvailable = response.isEmailAvailable;
          return isEmailAvailable ? null : {notAvailable: true};
        })
      );
    };
  }
validateEmail(control: AbstractControl)  {
    const value = control.value;
    return this.userService.checkEmail(value)
    .pipe(
      map(response => {
        const isEmailAvailable = response.isEmailAvailable;
        return isEmailAvailable ? null : {notAvailable: true};
      })
    );
  }

html

<p class="help is-danger" *ngIf="emailField.hasError('notAvailable')">
  Es correo esta ocupado
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment