Angular4 / Ionic3如何串行化数据

时间:2018-04-18 16:16:52

标签: angular authentication ionic3 token serializer

我在使用ionic 3 / Angular 4的应用程序中工作,我遇到登录功能问题。 我想从这里改变json格式:

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

这样的事情

  

grant_type =密码&安培; CLIENT_ID =客户机安培; client_secret =秘密&安培;用户名=管理员&安培;密码= 123456

所以我可以用它来进行令牌认证:

  

http://localhost:8080/api/oauth/token?grant_type=password&client_id=client&client_secret=secret&username=admin&password=123456

我在离子1 / angularJS中使用过它

  

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

但我不知道角度为4的等效物。

提前致谢:)

1 个答案:

答案 0 :(得分:1)

您必须使用URLSearchParams

基本示例

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

Set Search Parameters

您的服务

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