【发布时间】:2018-04-27 18:21:47
【问题描述】:
我正在验证服务器上是否存在手机号码 5.Si 我为此创建了一个自定义异步验证器。但它不工作也没有给出任何错误,并且它为表单字段提供待处理状态。任何帮助将不胜感激.这里是service.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)
},
);
}
);
}
}
【问题讨论】:
-
从 api 返回的数据是一个 json 数组,例如 {'status':'ok'}
标签: angular5