2016-12-14 52 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/

我希望這可以幫助你。