【问题标题】:Angular create Async Validator for unique userNameAngular为唯一的用户名创建异步验证器
【发布时间】:2021-11-29 06:41:46
【问题描述】:

我已经为 Async Validator 编写了服务代码,但我想为此编写通用指令。这是我的代码;

import { Directive } from '@angular/core';
import {AbstractControl, AsyncValidator, NG_ASYNC_VALIDATORS, ValidationErrors} from "@angular/forms";
import {Observable} from "rxjs";
import {IUser} from "app/core/user/user.model";
import {UserService} from "app/core/user/user.service";

@Directive({
  "selector": '[uniqueUsername][ngModel],[uniqueUsername][FormControl]',
  providers: [
    {provide: NG_ASYNC_VALIDATORS, useExisting: UniqueUsernameDirective, multi: true}
  ]
})
export class UniqueUsernameDirective implements AsyncValidator{

  constructor(private userService: UserService) { }

  validate(control: AbstractControl, currentUser?: IUser): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>{
    const promise = new Promise<any>((resolve, reject) => {
      if (currentUser?.login !== control.value) {
        this.userService.userExits(control.value).subscribe(user => {
            if (user?.login !== '') {
              resolve(null);
            }
          },
          response => {
            resolve({'loginAlreadyExits': true});
          });
      }
    });
    return promise;
  }

}

这是我得到的错误;

/Users/aygunozdemir/IdeaProjects/inuka-ng/src/main/webapp/app/shared/validators/unique-username.directive.ts 10:49 错误“UniqueUsernameDirective”在定义之前被使用@typescript-eslint/no-use-before-define

✖ 1 个问题(1 个错误,0 个警告)

这是我的文件; https://weblog.west-wind.com/posts/2019/Nov/18/Creating-Angular-Synchronous-and-Asynchronous-Validators-for-Template-Validation

另外,我怎样才能将输入添加到内部指令,基本上

   <input type="text" class="form-control" id="login" name="login" formControlName="login" uniqueUsername[???? shal I put here 'currentUser']>

【问题讨论】:

    标签: javascript angular typescript angular-directive customvalidator


    【解决方案1】:

    要在表单输入控件中使用 uniqueUsername 验证指令,请按如下方式应用它:

    <input type="text" class="form-control" id="login" name="login" 
        formControlName="login" uniqueUsername={{currentUser}}> 
    

    其中 currentUser 是您希望验证的组件中的一个变量。

    还记得在你的应用模块中声明你的验证指令:

    @NgModule({
      declarations: [
        . . . 
        UniqueUsernameDirective
      ],
      ...
    

    【讨论】:

    • 是的,我已经添加到模块中。问题是关于打字稿。有 @typescript-eslint/no-use-before-define 错误。但该文件没有说明这一点:)
    猜你喜欢
    • 2013-07-09
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多