Tu如何在Angular中将自定义验证器与服务一起使用

时间:2019-07-26 17:28:25

标签: angular typescript validation

我尝试使用自定义验证程序来检查是否已接收电子邮件。 根据文档和一些文章,我想到了以下代码:

在我的auth.service.ts中

checkEmail(email) {
    const r$ = of(true);
    const x$ = of(false);
    return this.http.post<any>(`${config.apiUrl}/users/email`, email)
    .pipe(
      mergeMap(v =>
        iif(
          () => v,
          r$,
          x$
        )
      )
    );
  }

在我的组件中

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.email,
        this.checkEmail.bind(this)
      ]]
    });
  }



checkEmail(control: AbstractControl) {
    if (control.value) {
      return this.authService.checkEmail({email: control.value}).toPromise()
      .then(response => {
        return response ? { forbiddenName: {value: control.value}} : null;
        });
    }
  }

但是它不起作用,如何使checkEmail()函数返回用于验证器的正确数据

1 个答案:

答案 0 :(得分:1)

您需要以下mod:

  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.email
      ], [this.checkEmail.bind(this)]] // async validators go separate after sync validators
    });
  }



  checkEmail(control: AbstractControl) {
    if (control.value) {
      return this.authService.checkEmail({email: control.value}).pipe(
        map(response => {
          return response ? { forbiddenName: {value: control.value}} : null;
         }) // use observables, don't convert to promises
       );
    }
    return of(null); // gotta return an observable for async
  }

不需要,但这也可以更简单/更简洁:

  checkEmail(email) {
    return this.http.post<any>(`${config.apiUrl}/users/email`, email)
    .pipe(
      map(v => !!v) // map and coerce to bool
    );
  }
相关问题