2017-01-29 33 views
1

是新形式的異步驗證,angular2,我想驗證來自服務器的電子郵件地址,但它沒有在angular2

這是我的形式

this.userform = this._formbuilder.group({ 
    email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this)]], 
}); 

然後_ValidationService我有 驗證服務是與@Injector

@Injectable() 
    export class ValidationService{ 

    constructor(
private _authService:AuthService 
){} 

emailExistsValidator(control) { 
    if (control.value != undefined) { 
    return this._authService.checkExists("email") 
     .map(response => { 
     if (!response) { 
      return {'emailNotExists': true}; 
     } 
     }); 
    } 
    } 
} 

服務而在authservice我有(其被另一服務執行HTTP請求)

@Injectable() 
export class AuthService { 

checkExists(value):Observable<any>{ 
return this._http.get(this.authurl+value) 
    .map(response => { 
    return response //this is either true or false 
    }); 
} 

} 

我已按照建立我的表格This link但它無法

返回的錯誤是

Cannot read property 'checkExists' of undefined 
at UsersComponent.webpackJsonp.187. 
ValidationService.emailExistsValidator 

可能是錯的什麼

+0

您需要爲您的代碼提供更多上下文。 'emailExistsValidator()'方法位於何處? 「this._authService」如何實例化? – AngularChef

+0

對不起更新的問題,這些都是不同的服務,this._authservice在構造函數中實例化 –

回答

1

如果this應指向ValidationServicebind()需要爲

this.userform = this._formbuilder.group({ 
    email: ['', [Validators.required], [this._validationService.emailExistsValidator.bind(this._validationService)]], 
}); 
+1

感謝溝它現在的作品 –

+0

現在的另一個問題,我想驗證只有在用戶完成輸入電子郵件後,目前的作品在每個按下的按鍵上,我該怎麼做 –

+0

只需隱藏驗證錯誤,而不希望用戶看到它。像'showEmailValidation:boolean = false;''' –