首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 4:使用自定义异步验证器,反应式表单控件处于挂起状态

Angular 4:使用自定义异步验证器,反应式表单控件处于挂起状态
EN

Stack Overflow用户
提问于 2018-02-07 11:05:49
回答 3查看 22K关注 0票数 24

我正在构建一个Angular 4应用程序,需要在几个组件的表单字段上的BriteVerify电子邮件验证。我正在尝试将此验证实现为一个自定义异步验证器,我可以将其与反应式表单一起使用。目前可以获取接口响应,但控制状态为挂起状态。我没有得到错误,所以我有点困惑。请告诉我我哪里做错了。这是我的代码。

组件

代码语言:javascript
复制
import { Component, 
         OnInit } from '@angular/core';
import { FormBuilder, 
         FormGroup, 
         FormControl, 
         Validators } from '@angular/forms';
import { Router } from '@angular/router';

import { EmailValidationService } from '../services/email-validation.service';

import { CustomValidators } from '../utilities/custom-validators/custom-validators';

@Component({
    templateUrl: './email-form.component.html',
    styleUrls: ['./email-form.component.sass']
})

export class EmailFormComponent implements OnInit {

    public emailForm: FormGroup;
    public formSubmitted: Boolean;
    public emailSent: Boolean;
    
    constructor(
        private router: Router,
        private builder: FormBuilder,
        private service: EmailValidationService
    ) { }

    ngOnInit() {

        this.formSubmitted = false;
        this.emailForm = this.builder.group({
            email: [ '', [ Validators.required ], [ CustomValidators.briteVerifyValidator(this.service) ] ]
        });
    }

    get email() {
        return this.emailForm.get('email');
    }

    // rest of logic
}

验证器类

代码语言:javascript
复制
import { AbstractControl } from '@angular/forms';

import { EmailValidationService } from '../../services/email-validation.service';

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

export class CustomValidators {

    static briteVerifyValidator(service: EmailValidationService) {
        return (control: AbstractControl) => {
            if (!control.valueChanges) {
                return Observable.of(null);
            } else {
                return control.valueChanges
                    .debounceTime(1000)
                    .distinctUntilChanged()
                    .switchMap(value => service.validateEmail(value))
                    .map(data => {
                        return data.status === 'invalid' ? { invalid: true } : null;
                    });
            }
        }
    }
}

服务

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { HttpClient,
         HttpParams } from '@angular/common/http';

interface EmailValidationResponse {
    address: string,
    account: string,
    domain: string,
    status: string,
    connected: string,
    disposable: boolean,
    role_address: boolean,
    error_code?: string,
    error?: string,
    duration: number
}

@Injectable()
export class EmailValidationService {

    public emailValidationUrl = 'https://briteverifyendpoint.com';

    constructor(
        private http: HttpClient
    ) { }

    validateEmail(value) {
        let params = new HttpParams();
        params = params.append('address', value);
        return this.http.get<EmailValidationResponse>(this.emailValidationUrl, {
            params: params
        });
    }
}

模板(只是表单)

代码语言:javascript
复制
<form class="email-form" [formGroup]="emailForm" (ngSubmit)="sendEmail()">
    <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
            <fieldset class="form-group required" [ngClass]="{ 'has-error': email.invalid && formSubmitted }">
                <div>{{ email.status }}</div>
                <label class="control-label" for="email">Email</label>
                <input class="form-control input-lg" name="email" id="email" formControlName="email">
                <ng-container *ngIf="email.invalid && formSubmitted">
                    <i class="fa fa-exclamation-triangle" aria-hidden="true"></i>&nbsp;Please enter valid email address.
                </ng-container>
            </fieldset>
            <button type="submit" class="btn btn-primary btn-lg btn-block">Send</button>
        </div>
    </div>
</form>

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-02-08 02:53:56

那有个!

也就是说,你的观察者永远不会完成...

发生这种情况是因为可观察对象永远不会完成,因此Angular不知道何时更改表单状态。所以记住你的观察者必须完成。

您可以通过多种方式完成此操作,例如,可以调用first()方法,或者如果您正在创建自己的observable,则可以对观察者调用complete方法。

因此您可以使用first()

RXJS6的更新:

代码语言:javascript
复制
briteVerifyValidator(service: Service) {
  return (control: AbstractControl) => {
    if (!control.valueChanges) {
      return of(null);
    } else {
      return control.valueChanges.pipe(
        debounceTime(1000),
        distinctUntilChanged(),
        switchMap(value => service.getData(value)),
        map(data => {
          return data.status === 'invalid' ? { invalid: true } : null;
        })
      ).pipe(first())
    }
  }
}

稍作修改的验证器,即总是返回错误:

旧版

代码语言:javascript
复制
.map(data => {
   return data.status === 'invalid' ? { invalid: true } : null;
})
.first();

稍作修改的验证器,即总是返回错误:

票数 31
EN

Stack Overflow用户

发布于 2020-01-21 15:35:26

所以我所做的就是在用户名没有被接受的时候抛出一个404,并使用订阅错误路径来解决null,当我得到一个响应时,我解决了一个错误。另一种方法是通过响应对象返回一个数据属性,该属性要么填充用户名宽度,要么为空,并使用404的insead

例如。

在本例中,我绑定( this )以便能够在验证器函数中使用我的服务

组件类ngOnInit()的摘录

代码语言:javascript
复制
//signup.component.ts

constructor(
 private authService: AuthServic //this will be included with bind(this)
) {

ngOnInit() {

 this.user = new FormGroup(
   {
    email: new FormControl("", Validators.required),
    username: new FormControl(
      "",
      Validators.required,
      CustomUserValidators.usernameUniqueValidator.bind(this) //the whole class
    ),
    password: new FormControl("", Validators.required),
   },
   { updateOn: "blur" });
}

从我的验证器类中摘录

代码语言:javascript
复制
//user.validator.ts
...

static async usernameUniqueValidator(
   control: FormControl
): Promise<ValidationErrors | null> {

 let controlBind = this as any;
 let authService = controlBind.authService as AuthService;  
 //I just added types to be able to get my functions as I type 

 return new Promise(resolve => {
  if (control.value == "") {
    resolve(null);
  } else {
    authService.checkUsername(control.value).subscribe(
      () => {
        resolve({
          usernameExists: {
            valid: false
          }
        });
      },
      () => {
        resolve(null);
      }
    );
  }
});

...
票数 2
EN

Stack Overflow用户

发布于 2018-04-17 22:47:49

我一直在以稍微不同的方式做这件事,并面临同样的问题。

以下是我的代码和修复,以防有人需要它:

代码语言:javascript
复制
  forbiddenNames(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve, reject) => {
      setTimeout(() => {
        if (control.value.toUpperCase() === 'TEST') {
          resolve({'nameIsForbidden': true});
        } else {

          return null;//HERE YOU SHOULD RETURN resolve(null) instead of just null
        }
      }, 1);
    });
    return promise;
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48655324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档