[英]Angular2 return data from validation service after Http call
我已經為我的注冊表單構建了一個驗證服務,其中一個靜態方法是通過調用我的API來檢查輸入的電子郵件是否可用:
static emailAvailable(control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
let valid = "E-mail is available";
http.post('https://secretapi.com/email', JSON.stringify({ email: control.value }))
.map((res: Response) => res.json())
.subscribe(function(result){
if(result.success){
valid = result.success; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return null; //Doesn't do anything?
}else{
valid = result.error; //The console.log on the line below is correct, the one at the bottom of the script never changes.
console.log(valid);
return { 'invalidEmailAddress': true }; //Doesn't do anything, just like the return above
}
});
console.log(valid); //Output always "E-mail is available"
}
當電子郵件可用時,它應該向表單驗證器返回“null”。 底部的最后一個console.log應該輸出它在訂閱調用中收到的消息。 這不會發生,我不知道為什么。 出於某種原因,訂閱調用中發生的所有事情都包含在那里,並且永遠不會到達驗證器。 我應該改變什么? 我不知道,現在正在網上搜索幾個小時。
您必須從驗證器返回Observable
或Promise
:
return http.post('https://secretapi.com/email', ...
console.log(...)
在這里沒有任何意義,因為它將在Observable
被創建為對象之后執行,但是在完成ajax
調用之后不會執行。
如果要在收到響應后輸出內容,則必須將其移至subscribe
所以最后這個網站得到了正確的答案。 同樣重要的是要注意Angular2 Form驗證器將Async驗證器放在第三個(3)參數中,而不是放在第二個(2)參數的數組中。 這花了我大約3個小時來弄明白。
function checkEmail(control:Control){
let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
let http = injector.get(Http);
return new Observable((obs: any) => {
control
.valueChanges
.debounceTime(400)
.flatMap(value => http.post('https://secretapi.com/email', JSON.stringify({ email: control.value })))
.map((res: Response) => res.json())
.subscribe(
data => {
if(data.success){
obs.next(null);
obs.complete();
} else {
obs.next({ 'invalidEmailAddress': true });
obs.complete();
}
}
);
});
}
驗證器應該看起來像這樣,第一個驗證器檢查是否需要,如果它實際上是一個電子郵件地址,並且最后一個對服務器執行異步調用以查看它是否尚未使用:
this.registerForm = this.formBuilder.group({
'email': ['', [Validators.required, ValidationService.emailValidator], ValidationService.emailAvailable],
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.