Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use httpparamserializer in Angular2

Tags:

angular

I am trying to use httpparamserializer in Angular2. I googled a lot but the examples are only for angular1 as shown below. How to inject $httpParamSerializer for use in templateUrl

What would be the syntax to use it in Angular2?

like image 466
vanval Avatar asked Oct 04 '16 17:10

vanval


2 Answers

I had the exact same question HERE

My Solution: I have a POST where I post data to a web service and I serialize my object this is how I do it. It is pretty simple and easy to use.

URLSearchParams

Basic example

let params = new URLSearchParams();
params.set('search', term); // the user's search value

Set Search Parameters

my-form-component.ts

import { Headers, RequestOptions, Http, Response, URLSearchParams } from '@angular/http';


// User is done editing, serialize and POST to web service
saveEdits(): void {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = new RequestOptions({ headers: headers });

    // Dynamically serialize the entire object
    // *** THIS IS THE SERIALIZATION ***
    let params: URLSearchParams = this.serialize(this.selectedItem);


    this._http.post('http://URLtoPOSTobjTo/path', params, options)
      .map(this.extractData)
      .catch(this.handleError);

}

/**
 * Serializes the form element so it can be passed to the back end through the url.
 * The objects properties are the keys and the objects values are the values.
 * ex: { "a":1, "b":2, "c":3 } would look like ?a=1&b=2&c=3
 * @param  {SystemSetup} obj - The system setup to be url encoded
 * @returns URLSearchParams - The url encoded system setup
 */
serialize(obj: SystemSetup): URLSearchParams {
    let params: URLSearchParams = new URLSearchParams();

    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            var element = obj[key];

            params.set(key, element);
        }
    }
    return params;
}
like image 62
Logan H Avatar answered Nov 17 '22 21:11

Logan H


URLSearchParams deprecated

Please see the HttpParams as replacement for URLSearchParams

The usage is a bit tricky because the HttpParams is immutable so if you want to append many things one after another you will have to do it like this.

var params = new HttpParams();
params = params.append('foo1', 'bar1');
params = params.append('foo2', 'bar2');
like image 43
Bartando Avatar answered Nov 17 '22 21:11

Bartando