【问题标题】:Angular Form custom validator http observable returning null on http callAngular Form自定义验证器http observable在http调用上返回null
【发布时间】:2020-04-01 03:40:33
【问题描述】:

我正在尝试设置一个表单字段来检查电子邮件是否存在。我已经查看了一些示例,并且验证工作正常,但是当我实现 http 管道时,映射到我的服务的 Observable,它会将其作为 null 抛出?我可以假设我从我的服务中错误地管道到它,但我不太确定。

有人可以帮助我吗?

core.js:6014 ERROR TypeError: Cannot read property 'emailService' of undefined

app.component.ts

export class AppComponent implements OnInit {

  signUpForm: FormGroup;

  constructor(private fb: FormBuilder, private emailService: EmailService) { }

  ngOnInit() {
    this.signUpForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required], [this.validateEmailNotTaken]]
    });
  }

  //Validator for checking if email name is taken or not
  validateEmailNotTaken(control: AbstractControl): Observable<{ [key: string]: any } | null> {

      if (control.value === null || control.value.length === 0) {
        return of(null);
      }
      else {
        return timer(1000).pipe(
          switchMap(() => {


            this.emailService.checkEmailExists(control.value).pipe(
              map(res => {
                //Do what with response
                console.log(res);

                if (!res) {
                  return { taken: true };
                }

                return of(null);
              })
            );


          })
        );
      }


  }

}

email.service.ts

 interface IServerCheckEmailExists {
    "available": boolean;
}
export interface ICheckEmailExists {
    taken: boolean;
}

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

    constructor(private _http: HttpClient) {
    }

    checkEmailExists(email: string): Observable<ICheckEmailExists[]> {

        var postObject = {"action": "checkEmailExists"};
        return this._http.post<IServerCheckEmailExists[]>("myapiurl/" + email, postObject).pipe(
            map(o => o.map((sp): ICheckEmailExists => ({
                taken: sp.available
            })))
        );
    }
}

【问题讨论】:

  • 您是否将 emailservice 正确导入到 appcomponent 中?
  • 要重现该问题,需要进行堆栈闪电战。
  • 是的,我在示例代码中省略了导入,但我有 import { EmailService } from '../_services';
  • 我是否正确访问了pipe(switchMap() 中的emailService.checkEmailExists()

标签: angular rxjs angular-forms angular-observable


【解决方案1】:

您的 validateEmailNotTaken 方法未获取组件的实例。创建 formGroup 时需要绑定它。像这样修改你的代码:-

this.signUpForm = this.fb.group({
  name: ['', Validators.required],
  email: ['', [Validators.required], [this.validateEmailNotTaken.bind(this)]]
});

请试试这个并告诉我。

【讨论】:

    【解决方案2】:

    我在您的代码中看到的唯一问题是您没有在switchMap 内返回对this.emailService.checkEmailExists(control.value) 的调用,因为您使用的是{},所以您应该这样做。像这样的:

    import { Component, OnInit } from "@angular/core";
    import {
      FormGroup,
      FormBuilder,
      Validators,
      AbstractControl
    } from "@angular/forms";
    import { Observable, of, timer } from "rxjs";
    import { switchMap, map } from "rxjs/operators";
    
    import { EmailService } from "./email.service";
    
    @Component({
      selector: "my-app",
      templateUrl: `./app.component.html`,
      styleUrls: [`./app.component.css`]
    })
    export class AppComponent implements OnInit {
      signUpForm: FormGroup;
    
      constructor(private fb: FormBuilder, private emailService: EmailService) {}
    
      ngOnInit() {
        this.signUpForm = this.fb.group({
          name: ["", Validators.required],
          email: ["", [Validators.required], [this.validateEmailNotTaken.bind(this)]]
        });
      }
    
      //Validator for checking if email name is taken or not
      validateEmailNotTaken(
        control: AbstractControl
      ): Observable<{ [key: string]: any } | null> {
        if (control.value === null || control.value.length === 0) {
          return of(null);
        } else {
          return timer(1000).pipe(
            switchMap(() => {
              // RIGHT HERE ??
              return this.emailService.checkEmailExists(control.value).pipe(
                map(res => {
                  //Do what with response
                  console.log(res);
                  if (res) {
                    return of(null);
                  }
                  return { taken: true };
                })
              );
            })
          );
        }
      }
    }
    

    这里有一个Working Code Example 供您参考。

    【讨论】:

    • 绑定是问题所在。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 2019-03-15
    • 2019-01-22
    • 1970-01-01
    • 2018-01-18
    • 2018-07-28
    • 1970-01-01
    • 2019-06-20
    相关资源
    最近更新 更多