【问题标题】:Angular4/Ionic3 how to Serializer dataAngular4/Ionic3如何序列化数据
【发布时间】:2018-09-28 23:27:05
【问题描述】:

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

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

这样的事情

?grant_type=password&client_id=client&client_secret=secret&username=admin&password=123456

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

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

我在 ionic 1 / angularJS 中使用它

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

但我不知道角度 4 中的等价物。

提前致谢:)

【问题讨论】:

    标签: angular authentication ionic3 token serialization


    【解决方案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;
    }
    

    【讨论】:

    • for function : SystemSetup 不知道,我必须改成什么?还是我需要导入一些东西??
    • 你可以改成任意的
    • Okey 谢谢工作正常,但我收到一个新错误:“错误”:“未授权”,“消息”:“访问此资源需要完全身份验证”
    • 不是后端问题。这只是登录功能的语法问题,现在可以正常工作了。谢谢你的回复:)
    猜你喜欢
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多