在Angular 2中成功提交表单后发送Httpclient POST

时间:2018-08-10 23:09:49

标签: angular forms typescript angular-httpclient

当前,当我提交表单时,不执行HttpClient POST。但是,如果我将e.preventDefault()添加到sendBreakdown()方法中,则POST将成功运行。尽管在这种情况下,表单不会在电子邮件<input>字段上提交或运行任何验证。

最终,我想向用户的HttpClient POST发送Data[]和用户输入表单的电子邮件地址。

问题:

a)如何在成功提交表单的情况下(且仅)运行HttpClient POST,而无需使用e.preventDefault

b)如何获取电子邮件字段,并将其与其他数据一起发送到POST请求?

finished.component.html

 <form class="form-group-submit">
  <div class="form-group">
   <input type="email" class="form-control" id="email" required  placeholder="Enter your Email Address">
   <button type="submit" class="btn btn-success submit-button" (click)="sendBreakdown($event)">Send Detailed Breakdown</button>
  </div>
 </form>

finished.component.ts

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {ApiService} from '../api.service';

@Component({
  selector: 'app-finished',
  templateUrl: './finished.component.html',
  styleUrls: ['./finished.component.scss'],
})
export class FinishedComponent implements OnInit {
  data = [
    {
      name: 'Testdata',
      capacity: 11,
      id: this.generateId()
    },
    {
      name: 'Testdata2',
      capacity: 101,
      id: this.generateId()
    }
  ];

  constructor(private apiService: ApiService) {
  }

  ngOnInit() {
  }

  sendBreakdown(e) {
    e.preventDefault();
    this.apiService.sendEmail(this.data).subscribe(
      (response) => console.log(response),
      (error) => console.log(error)
    );
  }

  private generateId() {
    return Math.round(Math.random() * 10000);
  }

}

api.service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

@Injectable()
export class ApiService {
  serverUrl = 'myServerUrlHere';

  constructor(private httpClient: HttpClient) { }

  sendEmail(data: any[]) {
    return this.httpClient.post(this.serverUrl, data);
  }

}

1 个答案:

答案 0 :(得分:0)

使用以下修改来获取电子邮件地址:

    <form class="form-group-submit">
  <div class="form-group">
   <input type="email" class="form-control" id="email" required  placeholder="Enter your Email Address" [(ng-model)]="EmailId">
   <button type="submit" class="btn btn-success submit-button" (click)=getById(PostId)"">Send Detailed Breakdown</button>
  </div>
 </form>

这将处理将2向模型绑定到您的EmailId的问题。您的ng-click指令将获取在输入元素中输入的正确值。在获取数据后,只需进行绑定即可,然后将其附加到您要发送的POST请求中。

第一个问题: 在您的.TS文件中添加EmailId变量。

EmailId : String;
finalData : any;

使您具有以下sendBreakdown函数:

sendBreakdown(e) {
finalData = angular.extend(this.data, JSON.stringify({"Email" : this.EmailId}));
this.apiService.sendEmail(this.finaldata).subscribe(
  (response) => console.log(response),
  (error) => console.log(error)
);

}