angular - 如何将值传递给验证器以便在角度 5 中保存服务调用?
问题描述
我有来自 ts 文件(组件)的以下代码:
ngOnInit() {
this.getTripNames();
}
getInstruments() {
this.tripService.getTripNames().subscribe(
data => { this.tripNames = data; },
err => console.error(err),
() =>
console.log(this.trips)
);
}
ngAfterViewInit() {
this.tripForm = new FormGroup({
newTripName: new FormControl('', {
validators: Validators.compose([
Validators.required,
Validators.minLength(3),
ValidateTrip.createValidator(this.tripNames)
]),
updateOn: 'blur'
})
});
}
如您所见,行程是在加载组件时获取的(它们显示在页面上以及控制台上),问题是这些值在Validator
处理时不可用。被createValidator
调用,但值未定义。我可以向验证器注入服务并再次从 restful 服务中获取值,但这没有任何意义。知道如何在this.tripNames
内部提供Validator
吗?谢谢。
解决方案
根据 http 请求或其他 observable 进行验证时,您需要使用asyncValidator 。
ngAfterViewInit() {
this.tripForm = new FormGroup ({
newTripName: new FormControl('', {
validators: Validators.compose([
Validators.required,
Validators.minLength(3)
]),
asyncValidators: [tripNamesValidator.bind(this)],
updateOn: 'blur'
})
});
}
tripNamesValidator() {
return this.tripService.getTripNames()
.map(tripNames=>{
return youCondition?null:{errorName: 'error message'};
});
}
推荐阅读
- php - 从 imagecreatefromstring() 捕获异常
- javascript - 使用 Axios 将表单数据发送到 Strapi 时出现网络错误
- c# - Helix Toolkit - 旋转 Model3DGroup 其中心
- actionscript-3 - 使用屏幕键盘时并非所有文本都显示
- css - 单页的 CSS 类选择器
- c++ - 为什么 std::sample 不是 constexpr?
- python - 减少嵌套 for 循环的执行时间
- javascript - 启动 npm start 时找不到 open(未安装 ENOGIT git)
- javascript - v-binding 内联样式不返回结果
- rxjs - rxjs 连续动态数量的 api 调用