2017-07-28 70 views
0

我有一个角4页,从用户获得输入。我确实对个别控件进行了验证。在提交时,我想做服务器验证(主要是重新检查所有验证),并将任何错误作为字段名称返回,如果失败,返回true或false。角4绑定HTTP响应typescript模型

我想这些错误映射到页面上的控件并显示为错误。我正在使用反应形式,服务器响应将使用与窗体控件相同的名称。

例如,控件名称是'name'。提交后,我得到一个回应,该名称是无效的。我想显示和控制下的错误消息。当提交错误显示在每个控件的旁边时,这很像MVC。

这是可能的,我将如何去生成一个可用于所有窗体的通用绑定。

+1

如果你能分享你的代码,这将是非常棒的 – brijmcq

回答

0
Yes, it is quite simple in angular. Here is an example how to do so. 

    1. HTML file. 

    <form [formGroup]="saveForm" (ngSubmit)="saveData()" > 
     <div> 
      <label>Name</label> 
      <input id="name" type="text" class="form-control" formControlName="name" tabindex="1"> 
     </div> 
     <div *ngIf="errror" > 
      <p>{{errorMsg}}</p> 
     </div> 

     <button type="submit" id="btnSave" >Save</button> 
    </form> 

2.In Component ts. 
a. Defined the formgroup & error message variable. 
    saveForm :FormGroup; 
    errror :boolean = false ; 
    errorMsg :any; 
b. Initialize form group. (You can defined client side validation here using angular validator) 
    this.saveForm = this.fb.group({ 
    name: [''] 
    }); 
c. On save data method you need to set the error bit true. 
saveData() { 
    let data = this.saveForm .value.name; 
    this._userService.save(data) // calling service here. 
     .subscribe(
     (response :any)=> { 
      console.log(response); 
      } 
     }, 
     (error :any) => { 
      this.error = true; 
this.errorMsg = error.error; // assigning server side errro to the variable. 
     } 
     ); 

    } 

That's done. 
+0

感谢Kamaal。这将工作。我希望能够使用所有形式的通用东西。所以如果我有一个有20个输入的表单,那么这些错误将自动从返回的对象映射到表单。如果一个项目存在于返回的对象中,那么这是一个错误,并且该消息必须出现在该框的旁边。是否有一些软件包或某些东西可以让服务器验证错误显示在表单上。我希望也可以通过使用form.control.valid属性来验证钩子到角度验证中,而不必自己管理错误。 – janB