0

在我当前的应用程序中,我正在尝试构建一个允许用户更改其电子邮件或用户名的表单。我在表单字段上有一个验证器,因此用户不能拥有与其他用户相同的用户名或密码。我用用户当前的用户名和电子邮件预先填写该字段,但是,如果我单击该字段删除一个字符然后重新应用它,我会触发警告文本。如果当前用户输入自己的用户名,如何使验证器不引发错误?

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)
        );
      }




}
4

1 回答 1

0

您需要实施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))
    );
  }
}

我强烈建议您checkEmailTaken在服务中创建如上所示,它返回一个Observable<boolean>

有关更多详细信息,请查看 Angular 文档中的“实现自定义异步验证器”。

于 2020-06-26T17:06:01.207 回答