Angular 来自 API 调用的 8 FormGroup 异步验证

Angular 8 FormGroup async validation from API call

I need to validate Unique product title, except the current product id.

请注意,我需要使用异步验证来验证 FormGroup - API 服务调用

该函数包含硬编码值 2,请忽略它。

产品-component.ts

ngOnInit() {
    this.productForm = this.fb.group({
      categoryId: ['', [Validators.required]],
      title: ['', [Validators.required]],
      description: [''],
      oldPrice: ['', [Validators.required, Validators.maxLength(10), Validators.pattern('^\d+$')]],
      newPrice: ['', [Validators.required, Validators.maxLength(10), Validators.pattern('^\d+$')]]
}, 
// {validators: ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)}
{asyncValidators: [ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)]}
);

验证 class:

export class ValidateUniqueProductTitle {

public static checkProductTitle(productService: ProductService, productId) {
    return (group: AbstractControl): Observable<ValidationErrors | null> => {
        return productService.checkExisting(group.controls['title'].value, productId)
                            .pipe(
                                debounceTime(200),
                                distinctUntilChanged(),
                                take(1),
                                map((data: boolean) => {
                                    console.log('checkExisting api called', data);
                                    return data ?  {title_exists: true} : null;
                                })
                            ); 
        }
}

Issue:

Validate class function is never called when I use this line:

{asyncValidators:[ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)]}

When I use this line, function gets called but API is not fired:

{validators: ValidateUniqueProductTitle.checkProductTitle(this.productService, 2)}

这是一个愚蠢的错误。应该使用 FormGroup 而不是 Abstract Control 输入 return.

验证 class:

export class ValidateUniqueProductTitle {

  public static checkProductTitle(productService: ProductService, productId) {
       return (group: AbstractControl): Observable<ValidationErrors | null> => {
            return productService.checkExisting(group.controls['title'].value, productId)
                        .pipe(
                            debounceTime(200),
                            distinctUntilChanged(),
                            take(1),
                            map((data: boolean) => {
                                console.log('checkExisting api called', data);
                                return data ?  {title_exists: true} : null;
                            })
                        ); 
    }
} 

此外,重要的是要注意:

Async validators are fired only when all sync validators return null.

我原以为所有验证错误(同步和异步)都会一起出现,但事实并非如此。