如何在Angular2中使用httpparamserializer

抓住

我正在尝试在Angular2中使用httpparamserializer。我在Google上搜索了很多,但是示例仅适用于angular1,如下所示。如何注入$ httpParamSerializer以在templateUrl中使用

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

洛根H

我在这里有完全相同的问题

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

URLSearchParams

基本例子

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

设置搜索参数

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章