使用类对象作为函数中的参数添加到数组

时间:2017-07-09 14:08:53

标签: javascript angular

我想做一个简单的基础,我可以将数字添加到数组中。我从Angular教程(link)改变了“英雄之旅”。我想要做的是不是将名称(字符串)传递给函数我想给出一个完整的类对象(User)。我使用用户输入他的姓名和姓氏的表格(如果他想要的话可​​以输入城市)。我不知道如何从输入到整个对象的功能,而不是字符串参数列表。这是我的代码: 的 form.html :         

  <div class="form-group">
    <label for="Name">Name</label>
    <input type="text" class="form-control" id="Name" required name="nameField" [(ngModel)]="ngModel"  #nameField="ngModel" > 
    <div [hidden]="nameField.valid || nameField.pristine" class="alert alert-danger">Name is required</div>
  </div>

  <div class="form-group">
    <label for="surname">surname</label>
    <input type="text" class="form-control" id="surname" required name="surnameField" ngModel #surnameField="ngModel"> 
    <div [hidden]="surnameField.valid || surnameField.pristine" class="alert alert-danger">Surname is required</div>
  </div>

  <div class="form-group">
    <label for="city">City</label>
    <input type="text" class="form-control" id="city" name="city" ngModel #cityField="ngModel" > 
  </div> 

  <button type="submit" class="btn btn-success" [disabled]="!userForm.form.valid">Submit</button>

</form>

提交时的功能

onSubmit(name: string, surname: string, city: string ): void{
name = name.trim();
surname = surname.trim();
city = city.trim();

this.myservice.create(name, surname, city)
  .then(newUser => this.arrayUsers.push(newUser));
}

功能在myservice内创建

private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/mainArray';  // URL to web api
create(name: string, surname: string, city?: string): Promise<User> {
return this.http
  .post(this.heroesUrl, JSON.stringify({name: name, surname:surname, city:city}), {headers: this.headers})
  .toPromise()
  .then(res => res.json().data as User);
}

1 个答案:

答案 0 :(得分:0)

声明ngModel属性以将每个输入绑定到表单:

例如:

<input type="text" class="form-control" id="name" ngModel required name="nameField" > 
<input type="text" class="form-control" id="surname" ngModel required name="surnameField" > 
<input type="text" class="form-control" id="city" ngModel required name="cityField" ngModel > 

form元素中,为表单指定一个名称,以便能够在组件中绑定它,并在onSubmit()方法中将表单添加为参数:

<form #f="ngForm" (ngSubmit)="onSubmit(f)" >

现在您应该能够使用f.value属性检索用户:

onSubmit(f: NgForm): void{

this.myservice.create(f.value)
  .then(createdUser=> this.arrayUsers.push(createdUser));
}

此处提供更多信息:https://angular.io/api/forms/NgModel