angular - 异步验证器未执行

标签 angular angular-validation angular-validator

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

对于我的 Angular (13.0.2) 应用程序,我创建了一个验证器来检查 URL 是否已在使用中(即 GET 不会返回 404)。然而,虽然我可以看到正在调用的函数,但我没有看到 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()])

干杯

关于angular - 异步验证器未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71430569/

相关文章:

angular - 如果发生错误,如何更改图像的来源?

javascript - 在 Angular 中使用 Rxjs 更新来自不同 Json 源的 Json 中的数据

angular - minLength 和 maxLength 验证器在 Angular7 响应式表单中不起作用

使用动态/更新参数的 Angular 7 自定义验证

Angular 4.3 - HttpClient 设置参数

javascript - Angular 自定义异步验证器不工作

angular - 响应式(Reactive)表单验证器在 Angular 中不起作用

angular - 如何使 Angular Reactive Form 也需要禁用输入?

Angular 6,this.formGroup.updateValueAndValidity()无法正常工作

javascript - Angular 2 了解 ViewContainerRef 与 TemplateRef 的用法