在我当前的应用程序中,我正在尝试构建一个允许用户更改其电子邮件或用户名的表单。我在表单字段上有一个验证器,因此用户不能拥有与其他用户相同的用户名或密码。我用用户当前的用户名和电子邮件预填充域,但是,如果我单击该域删除一个字符,然后重新应用它,我会触发警告文本。如果当前用户输入了自己的用户名,如何使验证器不会引发错误?
import { Injectable } from '@angular/core';
import { FormControl, AbstractControl } from '@angular/forms';
import { UserinfoService } from 'src/services&Validtors/userinfo.service';
import { map } from 'rxjs/operators';
import { HttpClient, HttpParams } from '@angular/common/http';
@Injectable()
export class EmailValidator {
    constructor(private http:HttpClient) { }
    validateEmailNotTaken(control: AbstractControl) {
        return this.checkEmailNotTaken(control.value).pipe(
          map(res => {
            return res ? null : { emailTaken: true };
          })
        );
      }
    
      
      checkEmailNotTaken(email: string) {
        return this.http.get("http://127.0.0.1:8000/accounts/UserDataEmail/").pipe(
          map((emailList: Array<any>) =>
            emailList.filter(user => user.email === email)
          ),
          map(email => !email.length)
        );
      }
}发布于 2020-06-27 01:06:01
您需要实现AsyncValidator
import {AbstractControl, AsyncValidator, ValidationErrors} from "@angular/forms";
import {Injectable} from "@angular/core";
import {Observable, of} from "rxjs";
import {catchError, map} from "rxjs/operators";
@Injectable({ providedIn: 'root' })
export class EmailValidator implements AsyncValidator {
  constructor(private emailService: YourEmailService) {}
  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    return this.emailService.isEmailTaken(control.value).pipe(
      map(isTaken => (isTaken ? { emailTaken: true } : null)),
      catchError(() => of(null))
    );
  }
}我强烈建议您在返回Observable<boolean>的服务中创建如上所示的checkEmailTaken
For further details, check "Implementing a custom async validator" in the Angular documentation.
https://stackoverflow.com/questions/62599067
复制相似问题