【发布时间】: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 个警告)
另外,我怎样才能将输入添加到内部指令,基本上
<input type="text" class="form-control" id="login" name="login" formControlName="login" uniqueUsername[???? shal I put here 'currentUser']>
【问题讨论】:
标签: javascript angular typescript angular-directive customvalidator