typescript Angular中的唯一用户名确认,数据返回类型为可从服务中观察到

pn9klfpd  于 2023-02-17  发布在  TypeScript
关注(0)|答案(1)|浏览(99)

//注册表页. ts

this.registerationForm = new FormGroup(
          {
            username: new FormControl(null,
              [
                Validators.required,
                Validators.minLength(3),
                Validators.maxLength(30),
                Validators.pattern('^[a-zA-Z-0123456789]*$'),
    
              ]
            ),

//帐户服务. ts

validateUsername(username: string): Observable<any> {
    return this.httpManager.post(authServer + "username-validator", new ValidateUsernameRequest(username)).pipe(
        map(
            (response: Response) => {
                return response.data;
            }
        )
    );
}

//注册表-页面. html

<ion-item [ngClass]="username==null ? 'at-beginning':''">
                <ion-label position="floating">Kullanıcı Adı</ion-label>
                <ion-input name="username" formControlName="username" inputmode="text" class="ion-text-lowercase"
                  placeholder="Kullanıcı Adı" (onchange)=(checkUsername($event)) (keypress)=(onKeyUp($event)) (keydown.space)="$event.preventDefault()">
                </ion-input>
              </ion-item>

              <div class="err" *ngIf="formControls.username.errors">
                <div *ngIf="formControls.username.errors.required">Kullanıcı adı zorunlu.</div>
                <div *ngIf="formControls.username.errors.minlength">Kullanıcı adınız çok kısa.</div>
                <div *ngIf="formControls.username.errors.maxlength">Kullanıcı adınız çok uzun.</div>
                <div *ngIf="formControls.username.errors.pattern">Kullanıcı adınız özel karakter içeremez.</div>
                <div *ngIf="formControls.username.errors.checkUsername">Kullanıcı adınız alınmış.</div>
              </div>

我试着为用户名编写一个验证器,每当用户对输入进行更改时,它都会检查用户名的可用性。我为此奋斗了两天,但我就是卡住了。我知道我需要使用一个异步函数来订阅来自accountService.validateUseranem(control.value)的数据,但不知何故,我未能使其工作。
有人能帮我一下吗?

k4emjkb1

k4emjkb11#

我做了以下操作并修复了我自己的问题。

已创建用户名验证器指令.ts

import { AbstractControl,  AsyncValidatorFn, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { AccountService } from 'src/app/services/yon/auth/account.service';

export function existingUsernameValidator(userService: AccountService): AsyncValidatorFn {
    return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
      return userService.validateUsername(control.value).pipe(map(
        (data) => {
            console.log("The result is : " + data)
          return (!data) ? { "usernameExists": true } : null;
        }
      ));
    };
  }

然后在用户名的验证器中使用它

this.registerationForm = new FormGroup(
          {
            username: new FormControl(null, {
              validators: [
                Validators.required,
                Validators.minLength(3),
                Validators.maxLength(20),
              ],
              asyncValidators: [existingUsernameValidator(this.accountService)],
              updateOn: 'change'
            }),
            email: new FormControl(null, {
              validators: [
                Validators.required,
                Validators.email],
              asyncValidators: [existingEmailValidator(this.accountService)],
              updateOn: 'change'
            }),

像这样

还有;
updateOn:'change'了解控件上的输入是否更改,并且每当输入更改时,它都会检查值以进行验证。
因为我需要向API发送请求并使用返回的值作为响应,所以我的验证器需要是异步验证器,并且sync和aysnc验证器需要根据我的理解进行拆分,就像我所做的那样。

相关问题