簡體   English   中英

Angular4 / Ionic3如何序列化數據

[英]Angular4/Ionic3 how to Serializer data

我正在使用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://本地主機:8080 / API /的OAuth /令牌grant_type =密碼&CLIENT_ID =客戶端與client_secret =秘密和用戶名=管理員和密碼= 123456?

我像這樣在ionic 1 / angularJS中使用了它

數據:$ httpParamSerializer($ scope.data);

但我不知道角度4中的等效項

提前致謝 :)

您將必須使用URLSearchParams

基本例子

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

設置搜索參數

您的服務

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