2016-12-14 64 views
1

我想创建一个异步自定义验证器来检查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") 
} 
} 

回答

0

我会改变验证的函数调用 new EmployeeValidators(this._HttpService).EmpIdCheck

我认为这个问题是关于DI,你可以尝试注入去依赖作为一个参数功能和调用de验证器是这样的(您可以将它添加到Validator.compose中,或者像你已经拥有的一样):

this.myForm = fb.group({ 
     empId: ['', Validators.compose([Validators.required, Validators.pattern("^[0-9]*$"), Validators.minLength(5), Validators.maxLength(5),EmployeeValidators.EmpIdCheck(this._HttpService)])], 
     password: ['', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(10)])] 
    }); 

此外,我认为你应该添加你的服务作为组件的提供者,但我认为最好的做法是在你的自定义验证器中作为提供者,你应该得到它的依赖关系,功能。

你可以阅读更多关于此这里:

https://auth0.com/blog/angular2-series-forms-and-custom-validation/

http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/

我希望这可以帮助你。