Ionic 2 Http post method sending null data to rest service

Hello,
I am trying to send data to java rest service using http post in Ionic 2. But at the server side I am receiving null data. I am using FormParams at the server side, so wanted to know out how to send Form data but not JSON String in http post request.

My code

import {Http,Headers,RequestOptions,URLSearchParams} from ‘@angular/http’;
import { Injectable } from ‘@angular/core’;
import ‘rxjs/add/operator/map’;

@Injectable()
export class MyService {

teamId: number=0;
teamName:string='XYZ'; 
teamSummary:string='Summary';
typeId:number=1;
createdBy:number=2;
teamStatusAI:string='Active';
contacts:number=4;
openOrclose:string='open';

static get parameters() {
    return [[Http]];
}


constructor(private http:Http) {
   
}

saveTeam()
{
  
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

let data={teamName: this.teamName,teamId: this.teamId,teamSummary: this.teamName,typeId: this.typeId,createdBy: this.createdBy,teamStatusAI: this.teamStatusAI,contacts: this.contacts,openOrclose: this.openOrclose};

    console.log(data);  
    var response=this.http.post('IP Address',data,{ headers: headers });

    return response;
}

}

If this is iOS, make sure you are using https, not http.

Nope , this is for Android Platform

Instead of sending your data object, encode your data object:

  let dataEncoded = Object.keys(data).map(function (key) {
      return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
   }).join('&');

and send the dataEncoded in your post request.

1 Like