Angular 在自定义验证器中使用Observable

Angular 在自定义验证器中使用Observable,angular,angular-reactive-forms,Angular,Angular Reactive Forms,因此,我正在创建一个验证器,用于检查用户名是否已被使用 我有以下自定义验证器定义: import { AbstractControl } from '@angular/forms'; import { AccountApi } from '../../api/service/account.api'; import { Injectable } from '@angular/core'; import { switchMap, mapTo, catchError } from 'rxjs/ope

因此,我正在创建一个验证器,用于检查用户名是否已被使用

我有以下自定义验证器定义:

import { AbstractControl } from '@angular/forms';
import { AccountApi } from '../../api/service/account.api';
import { Injectable } from '@angular/core';
import { switchMap, mapTo, catchError } from 'rxjs/operators';
import { of, timer } from 'rxjs';


@Injectable()
export class UsernameValidator {
  constructor(private api: AccountApi) {

  }

  exists(control: AbstractControl) {
    // this.api.checkUsernameIfExisting(control.value).subscribe((existing) => {
    //   control.setErrors({ exists: existing });
    // });

    // return null;

    return timer(100).pipe(
      switchMap(() => this.api.checkUsernameIfExisting(control.value).pipe(
          // Successful response, set validator to null
          mapTo(null),
          // Set error object on error response
          catchError(() => of({ exists: true }))
        )
      )
    );
  }
}
我就是这样使用它的:

 username: ['', [
    Validators.required,
    Validators.minLength(6),
    Validators.maxLength(30),
    this.usernameValidator.exists.bind(this.usernameValidator)
 ]],
我的问题是,为什么我的API上的调用没有被触发?我检查了表单是否正在调用exists()并调用它


谢谢

异步验证器应该在同步验证器之后

所以我会尝试这样的方法:

username: ['', [
  Validators.required,
  Validators.minLength(6),
  Validators.maxLength(30),
 ],
 this.usernameValidator.exists.bind(this.usernameValidator)
],

异步验证器应该在同步验证器之后

所以我会尝试这样的方法:

username: ['', [
  Validators.required,
  Validators.minLength(6),
  Validators.maxLength(30),
 ],
 this.usernameValidator.exists.bind(this.usernameValidator)
],

我会试试这个,稍后会给你回复:)我会试试这个,稍后会给你回复:)