问题描述
我在一个Angular proyect中,并且我使用的是反应形式。我想做的是添加我自己的验证器。为此,我需要检查ID是否存在于数据库中。因此,我使用了异步验证器。如果id已被另一个元素使用,则它必须返回错误。否则,该表格将有效。
这是验证器。
export class ValidadorOperationId {
static createValidatorOperationId(name,operationListService: OperationsListService,time: number = 500): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => {
return timer(time).pipe(
switchMap(() => operationListService.getoperationsByUuid(name,control.value)),map(res => {
return res ? { operationIdExist: true } : null
}
)
);
};
}
}
这就是我在组件中调用验证器的方式。
this.fb.group({
value: [this.operationDetails['operationid'],[Validators.required],ValidadorOperationId.createValidatorOperationId(this.nombre,this.operationListService)]
})
问题是控件具有status: pending
,但我不知道出了什么问题。
如果您需要更多代码,请问我。
有人可以帮助我吗?
- 角度版本:8.2.14
- Rxjs版本:6.5.3
更新22/10/2020
我检查了status:pending
仅在服务未返回任何内容时出现(错误404)
解决方法
即使遇到404错误,也请确保您的getOperationsByUuid
至少返回一个可观察的或应许的。这可能就是为什么它停留在挂起状态的原因,因为此函数不返回任何内容,因此您的可观察对象也不会发出。
注意抽头运算符。如果此日志无法打印,那就是它一直待命的原因,因为它永远无法解析。
export class ValidadorOperationId {
static createValidatorOperationId(name,operationListService: OperationsListService,time: number = 500): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => {
return timer(time).pipe(
switchMap(() => operationListService.getOperationsByUuid(name,control.value)),tap(res => console.log('this should print')),map(res => {
return res ? { operationIdExist: true } : null
}
),take(1) // not useful if getOperationsByUuid is an http call (http calls always complete)
);
};
}
}
,
要处理404
或任何其他http错误,可以使用RxJS的catchError运算符。以下是您的验证器的外观-
export class ValidadorOperationId {
static createValidatorOperationId(name,control.value)
.pipe(catchError(err => of(null))),// <-- this is what you need
map(res => {
return res ? { operationIdExist: true } : null
}
)
);
};
}
}