我正在尝试为 Slug 表单控件创建自定义验证器。 这是我的代码。
ngOnInit() {
this.slugCtrl.setAsyncValidators(this.slugValidator);
}
slugValidator(control: AbstractControl) {
const obs1 = control.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
map(val => {
this.isError = of(false);
if (val === ' ') {
this.isAvailable = of(false);
// this.slugCtrl.setErrors({ required: true });
return { required: true };
// obs.next({ required: true });
// obs.complete();
}
this.isAvailable = of(false);
if (this.slugCtrl.valid) {
this.store.dispatch(new SlugActions.checkSlug({ slug: val }));
}
console.log(val);
})
);
return obs1;
}
当验证器运行时,它会说无法读取未定义的属性 isError。这意味着“this”没有在 map 函数中传递。 我在这里做错了什么?
此外, 如何返回多个可观察值?因为我的 slug 验证需要从不同的资源检查很多内容,并且每个资源都会返回一个可观察值。 这是进一步的代码
this.store.select(getSlugsIsProcessingFail()).subscribe(data => {
this.store.select(getSlugsIsProcessingError()).subscribe(_err => {
if (_err === 'Server error') {
alert(
'There was an error processing your request. Please try again!'
);
this.isError = of(false);
} else if (_err.hasOwnProperty('message')) {
this.error = _err.message;
// this.slugCtrl.setErrors({ available: true });
this.isError = of(true);
return { required: true };
}
});
this.store.select(getSlugsIsProcessingSuccess()).subscribe(data => {
if (data) {
this.isAvailable = of(true);
// this.slugCtrl.setErrors(null);
return null;
}
});
});
最佳答案
您应该使用箭头函数将其与您的函数绑定(bind)
slugValidator = (control: AbstractControl) => {
...
}
关于javascript - "this"在 map 运算符 Angular 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52041751/