angular - 在 Angular 8 中进行同步调用
问题描述
我有一个要验证的输入字段。
我正在使用自定义验证器来检查该输入字段值的有效性。
在自定义验证器中,我正在使用输入字段值对端点进行休息调用,以检查输入的值是否有效。
问题是在从其余 API 返回验证结果时,httpClient get 调用以异步方式工作。输入字段验证器出现并且验证无法按预期工作。
有没有办法同步进行http调用。
我在自定义验证器中的 httpClient 调用代码:
labelNameValidators.ts:
import {FormControl } from '@angular/forms';
export function labelNameValidators(control: FormControl) {
if(control.value!=null) {
this.labelService.checklabelNameFormat(control.value)
.subscribe(
(data) => {
if (data === 'true') {
console.log('success', data);
return {'labelMsg': { 'message' : data}};
}
else {
console.log('failure', data);
return {'labelMsg': { 'message' : data}};
}
},
(err) => {
console.log('error', err);
return null;
}
)
}
}
标签.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class LabelService {
private nameFormatCheckApi = environment.nameFormatCheckApi;
constructor( private http: HttpClient ) { }
checklabelNameFormat(name: string){
return this.http.get(this.nameFormatCheckApi + '?name='+name);
}
}
解决方案
您可以为您的案例使用异步验证器。
this.form = new FormGroup({
fieldExample: new FormControl(
null, Validators.required, asyncValidator())
});
在这里,您是一个使用带有模板驱动表单和响应式表单的异步验证器的现场演示。
推荐阅读
- elasticsearch - 使用通配符的 ElasticSearch RestHighLevelClient 搜索不起作用
- javascript - 这个引导箱是如何创建的?
- snowflake-cloud-data-platform - 无法为使用 PEP 517 且无法直接安装的 snowflake-connector-python 构建轮子
- android - 按下按钮显示 Android In-App-Review 对话框?
- angular - 使用 ChangeDetectionStrategy.OnPush 策略重新渲染组件以改变值
- terraform - 成功应用 TF 后,Terraform EC2 实例不可用于 SSH(除非 SSH 配置)
- google-cloud-dataflow - 在 Cloud Dataflow 中限制对第三方的并发调用
- python - 尝试将浮点操作数和度数符号组合到同一个变量中
- c++ - Why does my custom allocator preform proportional to malloc?
- ios - URLSession dataTask / uploadTask splitting large uploads into multiple requests