2017-05-25 19 views
0

如何使用API​​調用進行表單驗證以檢查數據是否正確?每當我進入這個註冊頁面我喜歡的錯誤:Ionic2,Angular,使用API​​調用進行表單驗證

Cannot read property 'put' of undefined 
Cannot read property 'http' of undefined 

你可以指導我什麼是錯在我的代碼? HTML:

<ion-content padding> 
    <p *ngIf="submitAttempt" style="color: #ea6153;">Please fill out all details accurately.</p> 
    <ion-list inset> 
    <form [formGroup]="signupForm"> 
     <ion-item> 
     <ion-input formControlName="userName" [(ngModel)]="userName" placeholder="UserName" type="text"></ion-input> 
     </ion-item> 
     <ion-item> 
     <ion-input formControlName="email" [(ngModel)]="email" placeholder="Email" type="email"></ion-input> 
     </ion-item> 
     <ion-item> 
     <ion-input formControlName="password" [(ngModel)]="password" placeholder="Password" type="password"></ion-input> 
     </ion-item> 
    </form> 
    <button ion-button block (click)="register()">Register</button> 
    </ion-list> 
</ion-content> 

這是我的TS文件,這個代碼是內部構造:

this.signupForm = formBuilder.group({ 
     userName: ['', Validators.compose([Validators.required, Validators.pattern('[a-zA-Z]*')]), this.authService.checkUserName], 
     email: ['', this.authService.checkEmail], 
     password: [''] 
    }); 

this.authService是API調用的一類,這裏是調用的一個,看上去秒同只是與不同的地址:

checkUserName(control: FormControl): any { 
    return new Promise((resolve, reject) => { 

     let headers = new Headers(); 
     headers.append('Content-Type', 'application/json'); 

     this.http.put('http://localhost:63203/api/Customers/CheckIfUserExist', JSON.stringify(control.value), { headers: headers }) 
     .subscribe((res) => { 
      resolve(res); 
     }, (err) => { 
      reject(err); 
     }); 
    }); 
    } 
+3

的可能的複製[如何進入回調中正確的\'這\'背景?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this -context-inside-a-callback) – Pengyy

回答

1

你應該使用array function保持原來的上下文。

this.signupForm = formBuilder.group({ 
    userName: ['', Validators.compose([Validators.required, Validators.pattern('[a-zA-Z]*')]),() => this.authService.checkUserName()], 
    email: ['',() => this.authService.checkEmail()], 
    password: [''] 
}); 
+0

我認爲應該是'()=> this.authService.checkUserName()'或'this.authService.checkUserName.bind(this)' – echonax

+1

@echonax哦,我沒有提到,只需添加箭頭功能即可。 :P – Pengyy

+0

@echonax我試圖找到着名的重複問題,但失敗了,如果您現在可以將此問題標記爲重複。 :-) – Pengyy