异步验证器未执行

Async validator not executing

Stackblitz:https://angular-ivy-mhot2x.stackblitz.io

对于我的 Angular (13.0.2) 应用程序,我创建了一个验证器来检查 URL 是否已经在使用中(即 GET 没有return404)。但是,虽然我可以看到正在调用的函数,但我没有看到 HTTP 请求发生。我做错了什么?

验证者:

mport { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import {
  AsyncValidatorFn,
  AbstractControl,
  ValidationErrors,
} from '@angular/forms';
import { Observable, of } from 'rxjs';

// h/t: https://medium.com/@rinciarijoc/angular-custom-async-validators-13a648d688d8
@Injectable({
  providedIn: 'root',
})
export class UrlExistsService {
  constructor(private http: HttpClient) {}

  public urlExists(url: string): Observable<boolean> {
    console.debug(`Check url exists: ${url}`)
    if (!url) {
      return of(false)
    }
    return this.http
      .get(url, { observe: 'response', responseType: 'text' })
      .pipe(
        map((res) => {
          console.debug('Check URL result', { res });
          return res.status !== 404;
        })
      );
  }

  public urlDoesNotExistValidator() {
    const fn: AsyncValidatorFn = (
      control: AbstractControl
    ): Observable<ValidationErrors | null> => {
      return this.urlExists(control.value).pipe(
        map((result: boolean) => {
          console.debug('URL exists?', result);
          return result ? { urlExists: true } : null;
        })
      );
    };
    return fn;
  }
}

您需要添加 asyncValidators 作为 FormControl 构造函数的 3rd 参数。 docs

在你的例子中它应该是:

this.url = new FormControl('', [],[this.urlExistsService.urlDoesNotExistValidator()])

干杯