简体   繁体   English

使用angular 4发送表单数据

[英]Using angular 4 to send form-data

Hi I'm building a WordPress theme and I need to use contact form 7 plugin on it, but I can't figure out the correct way to send the form data to the plugin. 嗨,我正在构建一个WordPress主题,我需要在其上使用联系表单7插件,但是我不知道将表单数据发送到该插件的正确方法。

here is my post service: 这是我的邮政服务:

import {
  Injectable
} from '@angular/core';

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

@Injectable()
export class FormsService {
  constructor(private http: HttpClient) {}

  postForm(url, form) {
    return this.http.post(url, form, {
      headers: new HttpHeaders().set('Content-Type', 'multipart/form-data'),
    })
  }
}

and the component part that use the service: 以及使用该服务的组成部分:

onSubmit() {
    const fd = new FormData();
    fd.append('your-name', this.name);
    fd.append('your-email', this.email);
    fd.append('your-message', this.message);
    fd.append('your-subject', this.sumbject);

    const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;

    this.sendMsg.postForm(url, fd).subscribe(
      data => {
        console.log(data);
      },
      err => console.log({
        error: err
      })
    )

    this.submitted = true;
  }

At this point the server response that the message was submitted ok, but when I go to the WP admin page, non of the field get the values. 此时服务器响应消息已提交,但是当我转到WP admin页面时,没有该字段获取值。

But If I use postman with this url and params the form all works as I want. 但是,如果我使用带有此url和params的邮递员,则所有表单都可以按我的要求工作。

I also found another solution that works but its not the angular way as I want to be. 我还发现了另一个可行的解决方案,但它并不是我想要的成角度的方式。

the solution 解决方案

 onSubmit() {
    const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;
    this.submitted = true;
  }

 sendData(url) {
    let XHR = new XMLHttpRequest();
    const FD = new FormData();
    FD.append('your-name', this.name);
    FD.append('your-email', this.email);
    FD.append('your-message', this.message);
    FD.append('your-subject', this.subject);


    // Define what happens on successful data submission
    XHR.addEventListener('load', function(event) {
      alert('Yeah! Data sent and response loaded.');
    });

    // Define what happens in case of error
    XHR.addEventListener('error', function(event) {
      alert('Oups! Something went wrong.');
    });

    // Set up our request
    XHR.open('POST', url);

    // Send our FormData object; HTTP headers are set automatically
    XHR.send(FD);
  }

I found my solution, the problem was on the headers definitions of my service, the correct way is: 我找到了解决方案,问题出在我的服务的标头定义上,正确的方法是:

postForm(url, body) {
  var headers = new HttpHeaders();
  headers.append('Content-Type', 'application/form-data');
  return this.http.post(url, body, {headers: headers })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM