【问题标题】:Ionic2, Angular, Form validation with API callsIonic2、Angular、带有 API 调用的表单验证
【发布时间】:2017-05-25 07:39:44
【问题描述】:

如何通过 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);
        });
    });
  }

【问题讨论】:

标签: javascript angular typescript ionic2


【解决方案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: ['']
});

【讨论】:

  • 我觉得应该是() =&gt; this.authService.checkUserName()或者this.authService.checkUserName.bind(this)
  • @echonax 哦,我没提,加箭头功能就行了。 :P
  • @echonax 我试图找到著名的重复问题,但失败了,如果您现在可以将此问题标记为重复。 :-)
  • @echonax 是的!就是这样。
猜你喜欢
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多