如何在Angular2中使用httpparamserializer

前端之家收集整理的这篇文章主要介绍了如何在Angular2中使用httpparamserializer前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在Angular2中使用httpparamserializer.我google了很多,但这些例子仅适用于angular1,如下所示.
How to inject $httpParamSerializer for use in templateUrl

在Angular2中使用它的语法是什么?

解决方法

我有完全相同的问题 HERE

我的解决方案:我有一个POST,我将数据发布到Web服务,我序列化我的对象,这就是我的工作方式.它非常简单易用.

URLSearchParams

基本的例子

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

Set Search Parameters

我的外形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;
}

猜你在找的Angularjs相关文章