异步验证 - 无法从角度2中的自定义验证访问服务

时间:2016-12-14 09:52:09

标签: angular angular2-forms angular2-services

我正在尝试创建一个异步自定义验证程序来检查表单中是否已存在EmployeeId。为此我创建了一个自定义验证器并实现了一个服务来调用web api。

当我试图搜索EmployeeId时,我收到一条错误消息,指出无法读取未定义的属性“服务”

任何有想法如何做的人......

自定义验证器

 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")
}
}

1 个答案:

答案 0 :(得分:0)

我会更改Validator的函数调用   new EmployeeValidators(this._HttpService).EmpIdCheck

我认为问题在于DI,您可以尝试将de依赖项作为函数的参数注入,并像这样调用de Validator(您可以将其添加到de Validators.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)])]
    });

此外,我认为您应该将您的服务添加为组件的提供者,但我认为最好的做法是将它作为提供者放在您的自定义验证器中,您应该获得它将执行该功能的依赖性。 / p>

您可以在此处详细了解:

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

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

我希望这可以帮到你。