Sasquatch3o3 Sasquatch3o3 - 2 months ago 37
jQuery Question

JQuery .param() method for Angular 2?

Is there anything like this $.param() function from JQuery for Angular2?

I know Angular 1 specifically has a service like it, Angular1 Equivalent

I have checked the Angular 2 site here and they have a demo of a POST but they send a JSON in the body of the request.

My current, non working, attempt

saveEdits() {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
this._http.post("ajax/update-thingy", JSON.stringify(this.dataJson), options)
.map(this.extractData)
.toPromise()
.catch(this.handleError);
// update in Angular 1 using JQuery function
// $http({
// method : 'POST',
// url : 'ajax/update-thingy',
// data : $.param($scope.formData),
// headers: {'Content-Type': 'application/x-www-form-urlencoded'}
// });
}

extractData(res: Response) {
let body = res.json();
if (body === 'failed') {
body = [];
}
return body || [];
}
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead

return Promise.reject(errMsg);
}


Or if it is easier to get JQuery in my Angular2 maybe that is a way to go.

UPDATE

I did solve my own issue. Please see my answer below!

Answer

I don't understand the down vote but anyways, I did solve my own issue.

Here is what I did, I used URLSearchParams from Angular 2. It has worked out pretty well. Not at all complicated and easy to use.

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

saveEdits() {
    let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
    let options = new RequestOptions({ headers: headers });
    let params: URLSearchParams = this.serialize(this.myObj);
    this._http.post("ajax/update-thingy", params, options)
        .map(this.extractData)
        .toPromise()
        .catch(this.handleError);
    this.selectedBill = null;
}

serialize(obj: Thingy) {
    let params: URLSearchParams = new URLSearchParams();


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

            params.set(key, element);
        }
    }

    return params;
}