我想創建一個異步自定義驗證器來檢查EmployeeId是否已經存在於窗體中。爲此,我創建了一個自定義驗證器並實現了一個調用Web API的服務。異步驗證 - 無法從角度2訪問自定義驗證服務
當我試圖尋找我得到一個錯誤的僱員說無法讀取的不確定
任何人有想法財產「服務」如何做到這一點..
自定義驗證
import { FormControl } from '@angular/forms'
import { HttpService } from '../Services/app.service';
export class EmployeeValidators {
constructor(private service: HttpService) { }
EmpIdCheck(control: FormControl) {
this.service.LoginCheck(control.value).subscribe(
data => {
if (data.length == 0 || data.length == 1) {
resolve(null);
} else {
resolve({ EmpIdCheck: true });
}
},
err => {
resolve({ EmpIdCheck: true });
}
)
});
}
}
組件
export class LoginComponent {
myForm: FormGroup;
constructor(private _HttpService: HttpService, private fb: FormBuilder) {
this.myForm = fb.group({
empId: ['', Validators.compose([Validators.required, Validators.pattern("^[0-9]*$"), Validators.minLength(5), Validators.maxLength(5)]), new EmployeeValidators(this._HttpService).EmpIdCheck],
password: ['', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(10)])]
});
}
服務
@Injectable()
export class HttpService {
public LoginCheck = (datas): any => {
let body = JSON.stringify({ datas });
return this._http.post(this.actionUrl, datas, {headers: this.headers}).map(this.extractData)
.do(data => console.log(data))
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.Data || {};
}
private handleError(error: Response) {
console.log(error)
return Observable.throw(error.json() || "server error")
}
}