我正在验证服务器上是否存在角度为5.Si的移动号码我为此创建了一个自定义异步验证器。但是它没有工作也没有给出任何错误,它给表单字段提供待处理状态。任何帮助将不胜感激。是服务代码.ts
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import { Observable } from "rxjs/Observable";
@Injectable()
export class SignupService {
constructor(private _http:HttpClient) {}
mobileExists(mobile:number):Observable<{}>{
return this._http.get("http://localhost/truck/api/web/user/verify- exist?mobile="+mobile,{responseType:'json'});
}
}
这是我的component.ts的代码
import { Component, OnInit } from '@angular/core';
import {FormsModule, ReactiveFormsModule,AbstractControl, ValidationErrors,FormControl,Validators,FormGroup,AsyncValidatorFn} from "@angular/forms";
import {SignupService} from "./signup.service";
import {Observable} from "rxjs/Observable";
import {map,take,debounceTime} from "rxjs/operators";
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css'],
providers: [SignupService]
})
export class RegisterComponent implements OnInit {
signupForm: FormGroup;
mobile: number;
password: string;
otp: number;
public exist;
constructor(public service:SignupService) {
}
ngOnInit() {
this.signupForm = new FormGroup({
mobile: new FormControl('',
[Validators.required, Validators.minLength(10), Validators.maxLength(10)],this.mobileValidator.bind(this)),
password: new FormControl('',
[Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
otp: new FormControl('',
[Validators.required, Validators.minLength(6), Validators.maxLength(6)]),
});
}
mobileValidator(control: AbstractControl):any {
return new Observable(resolve => {
this.service.mobileExists(control.value).subscribe(
data=>{
if (data['status'] == 'ok'){
return null;
}else if(this.exist.status == 'exist'){
return {mobileTaken:true};
}
},
error=>{
return console.log(error)
},
);
}
);
}
}
答案 0 :(得分:0)
mobile: new FormControl('',
[Validators.required, Validators.minLength(10), Validators.maxLength(10)],[this.mobileValidator()]),
所以 AsyncValidator 作为第三个参数,无需调用bind。使用map,无需换行到新的Observable调用:mobileValidator() { return (control: AbstractControl): any => { return this.service.mobileExists(control.value).map(data => return (data['status'] == 'ok') ? null : { mobileTaken: true } )); } }