【问题标题】:Angular2 - formData values are passed as null to HTTP POSTAngular2 - formData 值作为 null 传递给 HTTP POST
【发布时间】:2017-11-03 18:23:49
【问题描述】:

我将我的数据发布到邮递员服务,它工作正常。但是当我在 HTTP 发布请求中调用该服务时,它在控制台中显示成功,但 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>

【问题讨论】:

标签: angular http typescript post angular2-forms


【解决方案1】:

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

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

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

@Jamshed 的回答应该是正确的。但是如果你需要通过Headers传递user_namepassword,你可以像这样创建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);
  }

【讨论】:

    【解决方案2】:

    将表单值(带文件)附加到 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>
    

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 2022-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      相关资源
      最近更新 更多