简体   繁体   English

Angular4 / Ionic3如何序列化数据

[英]Angular4/Ionic3 how to Serializer data

I'm working in app with ionic 3 / Angular 4 and I have a problem with log-in function. 我正在使用ionic 3 / Angular 4在应用中工作,登录功能有问题。 I want change the json format from this: 我想从此更改json格式:

> this.data = {
>               grant_type: "password",
>               username: this.loginData.username,
>               password: this.loginData.password,
>               client_id: "client"
>               };

to something like this 像这样

?grant_type=password&client_id=client&client_secret=secret&username=admin&password=123456 ?grant_type =密码&CLIENT_ID =客户端与client_secret =秘密和用户名=管理员和密码= 123456

so I can use it for token authentication like that: 所以我可以将其用于令牌身份验证,如下所示:

http://localhost:8080/api/oauth/token?grant_type=password&client_id=client&client_secret=secret&username=admin&password=123456 HTTP://本地主机:8080 / API /的OAuth /令牌grant_type =密码&CLIENT_ID =客户端与client_secret =秘密和用户名=管理员和密码= 123456?

I used it in ionic 1 / angularJS like that 我像这样在ionic 1 / angularJS中使用了它

data: $httpParamSerializer($scope.data); 数据:$ httpParamSerializer($ scope.data);

but I don't know the equivalent in angular 4. 但我不知道角度4中的等效项

Thanks in advance :) 提前致谢 :)

You will have to use URLSearchParams 您将必须使用URLSearchParams

Basic example 基本例子

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

Set Search Parameters 设置搜索参数

Your Service 您的服务

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


// User is done editing, serialize and POST to web service
tokenAuthenticate(): 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://localhost:8080/api/oauth/token', 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 obj - Object to be url encoded
 * @returns URLSearchParams - The url encoded system setup
 */
serialize(obj: any): 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM