Angular2 - formData值作为null传递给HTTP POST

时间:2017-06-02 10:57:15

标签: angular http typescript post angular2-forms

我发布我的数据到邮递员服务它工作正常。但是当我在HTTP post请求中调用该服务时,它在控制台中显示成功但是formData变为null并且没有任何内容保存在服务器上。

任何帮助将不胜感激。我的代码:

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http } from '@angular/http';
import { Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/catch';

@Component({
  selector: 'login-page',
  templateUrl: './add.html'
})
export class ConfigComponent {
constructor(private http:Http) {
    this.news = {
      'newstitle': 'Test Title',
      'newsdescription': 'Test',
      'newstype': 'Test',
      'priority': 'Test',
      'place': 'Test',
      'publishedon': 'Test',
      'publishedby': 'Test',
      'websiteurl': 'Test',
      'contactpersonname': 'Test',
      'mobile1': 'Test',
      'mobile2': 'Test',
      'email': 'Test',
      'display': 'Test',     
      'rating': 'Test'
    };
  }

  onSubmit() {
    let formData:FormData = new FormData(this.news);
    console.log(this.news);
    let headers = new Headers({'encrypt': 'multipart/form-data'});
    let options = new RequestOptions({ headers: headers });  
    this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
  }
  }

Add.html

<h2>ADD CONFIGS</h2>
  <div class="row">
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    <div class="form-group col-xs-6">
      <label for="newstitle">NEWS TITLE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newsdescription">NEWS DESCRIPTION:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newsdescription" id="newsdescription" name="newsdescription"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newstype">NEWS TYPE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstype" id="newstype" name="newstype"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="priority">PRIORITY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.priority" id="priority" name="priority"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="place">PLACE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.place" id="place" name="place"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedon">PUBLISHED ON:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedon" id="publishedon" name="publishedon"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="publishedby">PUBLISHED BY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedby" id="publishedby" name="publishedby"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="websiteurl">WEBSITE URL:</label>
      <input type="text" class="form-control" [(ngModel)]="news.websiteurl" id="websiteurl" name="websiteurl"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="contactpersonname">CONTACT PERSON NAME:</label>
      <input type="text" class="form-control" [(ngModel)]="news.contactpersonname" id="contactpersonname" name="contactpersonname"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="mobile1">MOBILE 1:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile1" id="mobile1" name="mobile1"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="mobile2">MOBILE 2:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile2" id="mobile2" name="mobile2"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="email">EMAIL:</label>
      <input type="email" class="form-control" [(ngModel)]="news.email" id="email" name="email"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="status">STATUS:</label>
      <input type="text" class="form-control" [(ngModel)]="news.status" id="status" name="status"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="display">DISPLAY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.display" id="display" name="display"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="rating">RATING:</label>
      <input type="text" class="form-control" [(ngModel)]="news.rating" id="rating" name="rating"/>
    </div>                                    

    <div class="form-group col-xs-6">
            <label for="usr">City Image:</label>
            <img width="50px" height="50px" id="cimage">
            <input type="file" (change)="fileChange($event)" placeholder="Upload file">
    </div>       

    <button type="submit" class="btn btn-success">Add</button>

  </form>
</div>

enter image description here

2 个答案:

答案 0 :(得分:1)

将形式值(带文件)附加到ANGULAR2中的FORMDATA。

实际上有人发布了我的问题的答案,实际归功于他,我做了一些修改,将对象附加到形成数据以使其正常工作。 人们可以直接附加表单数据或迭代对象以向formData添加值。 以下是我的工作代码:

<强> Component.ts

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { Http } from '@angular/http';
import { Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/catch';

@Component({
  selector: 'login-page',
  templateUrl: './add.html'
})
export class ConfigComponent {
news;
fileList;
constructor(private http:Http) {
    this.news = {
      'newstitle': 'Test Title',
      'newsdescription': 'Test Title',
      'newstype': 'Test Title',
      'priority': 'Test Title',
      'place': 'Test Title',
      'publishedon': 'Test Title',
      'publishedby': 'Test Title',
      'websiteurl': 'Test Title',
      'contactpersonname': 'Test Title',
      'mobile1': 'Test Title',
      'mobile2': 'Test Title',
      'email': 'Test Title',
      'status': 'Test Title', 
      'display': 'Test Title',     
      'rating': 'Test Title'
    };
  }

      fileChange(event) {
        this.fileList = event.target.files;
      }

  onSubmit() {
    let formData:FormData = new FormData();

    formData.append('newstitle', this.news.newstitle);
    formData.append('newsdescription', this.news.newsdescription);
    formData.append('newstype', this.news.newstype);
    formData.append('priority', this.news.priority);
    formData.append('place', this.news.place);
    formData.append('publishedon', this.news.newstitlpublishedone);
    formData.append('publishedby', this.news.publishedby);
    formData.append('websiteurl', this.news.websiteurl);
    formData.append('contactpersonname', this.news.contactpersonname);
    formData.append('mobile1', this.news.mobile1);
    formData.append('mobile2', this.news.mobile2);
    formData.append('email', this.news.email);
    formData.append('status', this.news.status);
    formData.append('display', this.news.display);
    formData.append('rating', this.news.rating);

    if(this.fileList.length > 0){
      for (var x = 0;  x < this.fileList.length; x++) {
      let file: File = this.fileList[x];
      formData.append('fileData', file, file.name);
      }
      let headers = new Headers({'encrypt': 'multipart/form-data'});
      let options = new RequestOptions({ headers: headers });  
      this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
    } else {
      let headers = new Headers({'encrypt': 'multipart/form-data'});
      let options = new RequestOptions({ headers: headers });  
      this.http.post('SERVICE URL', formData, options)
        .subscribe(
            data => console.log(data),
            error => console.log(error)
        );
    }
  }
}

<强> ADD.html

<h2>ADD CONFIGS</h2>
  <div class="row">
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    <div class="form-group col-xs-6">
      <label for="newstitle">NEWS TITLE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newsdescription">NEWS DESCRIPTION:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newsdescription" id="newsdescription" name="newsdescription"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="newstype">NEWS TYPE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstype" id="newstype" name="newstype"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="priority">PRIORITY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.priority" id="priority" name="priority"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="place">PLACE:</label>
      <input type="text" class="form-control" [(ngModel)]="news.place" id="place" name="place"/>
    </div>

    <div class="form-group col-xs-6">
      <label for="publishedon">PUBLISHED ON:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedon" id="publishedon" name="publishedon"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="publishedby">PUBLISHED BY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.publishedby" id="publishedby" name="publishedby"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="websiteurl">WEBSITE URL:</label>
      <input type="text" class="form-control" [(ngModel)]="news.websiteurl" id="websiteurl" name="websiteurl"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="contactpersonname">CONTACT PERSON NAME:</label>
      <input type="text" class="form-control" [(ngModel)]="news.contactpersonname" id="contactpersonname" name="contactpersonname"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="mobile1">MOBILE 1:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile1" id="mobile1" name="mobile1"/>
    </div>                

    <div class="form-group col-xs-6">
      <label for="mobile2">MOBILE 2:</label>
      <input type="text" class="form-control" [(ngModel)]="news.mobile2" id="mobile2" name="mobile2"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="email">EMAIL:</label>
      <input type="email" class="form-control" [(ngModel)]="news.email" id="email" name="email"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="status">STATUS:</label>
      <input type="text" class="form-control" [(ngModel)]="news.status" id="status" name="status"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="display">DISPLAY:</label>
      <input type="text" class="form-control" [(ngModel)]="news.display" id="display" name="display"/>
    </div>                                    

    <div class="form-group col-xs-6">
      <label for="rating">RATING:</label>
      <input type="text" class="form-control" [(ngModel)]="news.rating" id="rating" name="rating"/>
    </div>                                    

    <div class="form-group col-xs-6">
            <label for="usr">City Image:</label>
            <img width="50px" height="50px" id="cimage">
            <input type="file" id="newsimg" name="newsimg" multiple="true" (change)="fileChange($event)">
    </div>             

    <button type="submit" class="btn btn-success">Add</button>

  </form>
</div>

答案 1 :(得分:0)

首先,遇到这种情况时,您应该检查formData是否已正确创建。一个简单的方法是:

console.log(formData.get('newstitle')) // check 'newstitle' field

您还可以查看formData对象中的其他字段。

@Jamshed的答案应该是正确的。但是,如果您需要将user_namepassword传递给Headers,则可以像这样创建options

  createAuthorizationHeader(headers: Headers, name: string, pw: string) {
    headers.append('Authorization', 'Basic ' +
      btoa(`${name}:${pw}`)); 
  }
  createOptions(name: string, pw: string) {
    let headers = new Headers();
    this.createAuthorizationHeader(headers, name, pw);
    // headers.append('Content-Type', 'multipart/form-data');  // <--- we can do post without this item.
    let options = new RequestOptions({ headers: headers });
    return options;
  }

然后可以这样做post

private imageUrl = 'http://192.168.201.211:8024/images/';
post(formData: FormData, user: string, pw: string): Promise<MyForm> {
    let options = this.createOptions(user, pw);
    console.log('we will have a post!');
    return this.http.post(this.imageUrl, formData, options)
                    .toPromise()
                    .then(res => res.json() as MyForm)
                    .catch(this.handleError);
  }