[英]Angular create Async Validator for unique userName
I already code service for Async Validator but I want to code generic Directive for this.我已经为 Async Validator 编写了服务代码,但我想为此编写通用指令。 Here is my code;这是我的代码;
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;
}
}
Here is what I am getting error;这是我遇到的错误;
/Users/aygunozdemir/IdeaProjects/inuka-ng/src/main/webapp/app/shared/validators/unique-username.directive.ts 10:49 error 'UniqueUsernameDirective' was used before it was defined @typescript-eslint/no-use-before-define /Users/aygunozdemir/IdeaProjects/inuka-ng/src/main/webapp/app/shared/validators/unique-username.directive.ts 10:49 错误 'UniqueUsernameDirective' 在定义之前被使用 @typescript-eslint/no-使用前定义
✖ 1 problem (1 error, 0 warnings) ✖ 1 个问题(1 个错误,0 个警告)
Here is my document;这是我的文件; https://weblog.west-wind.com/posts/2019/Nov/18/Creating-Angular-Synchronous-and-Asynchronous-Validators-for-Template-Validation https://weblog.west-wind.com/posts/2019/Nov/18/Creating-Angular-Synchronous-and-Asynchronous-Validators-for-Template-Validation
Also how can I add input to inside directive, basically另外我怎么能添加输入到内部指令,基本上
<input type="text" class="form-control" id="login" name="login" formControlName="login" uniqueUsername[???? shal I put here 'currentUser']>
To use your uniqueUsername validation directive within your form input control apply it as follows:要在表单输入控件中使用uniqueUsername验证指令,请按如下方式应用它:
<input type="text" class="form-control" id="login" name="login"
formControlName="login" uniqueUsername={{currentUser}}>
Where currentUser is a variable within your component that you wish to validate.其中currentUser是您希望验证的组件中的变量。
Also remember to declare your validation directive within your application module:还请记住在您的应用程序模块中声明您的验证指令:
@NgModule({
declarations: [
. . .
UniqueUsernameDirective
],
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.