Angular 如何映射服务器对错误和成功的响应
我正在尝试为我的Angular 9项目制作一个自定义验证器 这是验证器方法Angular 如何映射服务器对错误和成功的响应,angular,Angular,我正在尝试为我的Angular 9项目制作一个自定义验证器 这是验证器方法 public static validatName(service: MyService): AsyncValidatorFn { return (control: AbstractControl): Observable<ValidationErrors> => service.searchNumber(control.value) .pipe( map((resp
public static validatName(service: MyService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => service.searchNumber(control.value)
.pipe(
map((response) => response ? null : { notFound: true })
);
}
公共静态验证名(服务:MyService):AsyncValidatorFn{
return(control:AbstractControl):Observable=>service.searchNumber(control.value)
.烟斗(
map((response)=>response?null:{notFound:true})
);
}
当服务器响应404错误代码时,映射将不执行,并且我的表单控件未获得所需的验证null/not found
我如何映射我的服务器响应,无论是成功还是错误。
当我得到200时,它应该检索null,否则notFound:true
目前,只有200状态码方案有效您需要捕获异常
public static validatName(service: MyService): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors> => service.searchNumber(control.value)
.pipe(
map((response) => null),
catchError(() => of({ notFound: true })), // here
);
}
公共静态验证名(服务:MyService):AsyncValidatorFn{
return(control:AbstractControl):Observable=>service.searchNumber(control.value)
.烟斗(
映射((响应)=>null),
catchError(()=>of({notFound:true})),//此处
);
}