Stackblitz:https://angular-ivy-mhot2x.stackblitz.io
对于我的 Angular (13.0.2) 应用程序,我创建了一个验证器来检查 URL 是否已在使用中(即 GET
验证器:
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/