httpParamSerializerJQLike in angular2?

How to serialize JSON for Ruby API?

Angular 1

$scope.submitForm = function() {       
    var data = {"contato": $scope.contato, "id":$scope.contato.id, "_method":'PUT'};
    $http.post(
        'http://myApi/contatos/' + $scope.contato.id,
        **$httpParamSerializerJQLike(data)**,
        {
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            datatype: "JSONP"
        }).then(function successCallback(response) {
            modalContato.show();
            setTimeout(function (){
                modalContato.hide();
                $state.go('contato-detalhe', {"id":$scope.contato.id});
            }, 1500);              

    });
};    

Angular2:

insertContato(contato: Contato) {
  let headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'        
  });      
  let options = new RequestOptions({ headers: headers });
  this._http    
    .post(this.urlApi + '/contatos', JSON.stringify(contato), options)      
    .subscribe(data => {
      console.log('Funciona: ' + data.text());
    }, error => {
      console.log('Erro: ' + error.text())
    });           
}

“JSON.stringify(contato)”
It does not have the same behavior as $httpParamSerializerJQLike(data).
Json’s broken in the server…

Started POST “/contatos” for 127.0.0.1 at 2016-04-13 13:25:55 -0300
Processing by ContatosController#create as HTML
Parameters: {“{“nome”:”asd”,”email”:”asd@asda.com”,”telefone”:”123″}”=>nil}
Completed 400 Bad Request in 4ms (ActiveRecord: 0.0ms)

Correct is:

Started POST “/contatos” for 127.0.0.1 at 2016-04-12 17:00:24 -0300
Processing by ContatosController#create as JSON
Parameters: {“contato”=>{“nome”=>”felipe”, “telefone”=>”5555”}}
Completed 200 OK in 278ms (Views: 0.1ms | ActiveRecord: 229.4ms)

5
Leave a Reply

avatar
5 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

I had a similar problem, i can solve this: import { Headers, Http, Response, URLSearchParams, RequestOptions } from '@angular/http'; let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': '*/*'}); let options = new RequestOptions({ headers: headers }); let body = new URLSearchParams(); body.set("message", JSON.stringify(m_dataRequest)); body.set("webService", "authService"); return this.http .post(this.Url, body.toString(), options) .toPromise() .then(this.extractData) .catch(this.handleError); URLSearchParams normalized the params of the form and the pipes dimiss, this work for me. I hope this solve your problem.

Jason
Guest

I’m going to preface this by saying that this may not be the best way to handle this, but it’s how I took care of the problem for myself (The Angular 2 docs don’t seem to mention x-www-form-urlencoded anywhere). So if your data is set up like var data = {"contato": $scope.contato, "id":$scope.contato.id, "_method":'PUT'}; You want to basically convert it to a form yourself. var encodedData = "contato=" + contato + "&id=" + contato.id + "&_method=PUT"; then you can modify your POST request to look like this this._http .post(this.urlApi + '/contatos', encodedData, options) .subscribe(data => { console.log('Funciona: ' + data.text());… Read more »

Jason
Guest

I wrote a function in my http.ts provider like so — private formatData(data){ let returnData = ''; console.log(data); let count = 0; for (let i in data){ if(count == 0){ returnData += i+'='+data[i]; }else{ returnData += '&'+i+'='+data[i]; } count = count + 1; console.log(returnData); } return returnData; } Call it like this. post('localhost/url',data){ data = this.formatData(data); }

Jason
Guest

Just copy the relative codes from angularjs http module import { isArray, forEach, isObject, isDate, isFunction, isUndefined, isNumber, } from 'lodash'; function toJsonReplacer(key, value) { let val = value; if ( typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$' ) { val = undefined; } return val; } function toJson(obj, pretty = undefined) { if (isUndefined(obj)) return undefined; if (!isNumber(pretty)) { pretty = pretty ? 2 : null; // tslint:disable-line no-parameter-reassignment } return JSON.stringify(obj, toJsonReplacer, pretty); } function serializeValue(v) { if (isObject(v)) { return isDate(v) ? v.toISOString() : toJson(v); } return v; } function forEachSorted(obj, iterator,… Read more »

Jason
Guest

I’ve met the similar issue when was upgrading from angular 1.x Here is my solution which also process nested JSON objects: function Json2FormEncoded(json_obj) { let path = arguments[1] || ''; let s = '', p = ''; for (let i in json_obj) { p = path == '' ? i : path + '[' + i + ']'; s = s ? s + "&" : s; if (typeof json_obj[i] == 'object') { s += Json2FormEncoded(json_obj[i], p); } else { s += p + '=' + encodeURIComponent(json_obj[i]); } } return s; } Hope you’ll find it useful! Also check it… Read more »