Alessandro Celeghin
Alessandro Celeghin

Reputation: 4199

Angular 2 GET parameters remains empty

Hi i want to send parameters within a GET request but my search parameters remains empty, this is my code:

        private jwt2() {
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        console.log('current.token ' + currentUser.token);

        let params: URLSearchParams = new URLSearchParams();        //PARAMS
        params.set('pageSize', '6');            //pageSize

        let headers = new Headers({ 'Authorization': currentUser });
        console.log("params: " + params);    //here I can see correct params

        return new RequestOptions({ headers: headers, search: params });
        //  }
    }

I can see the correct headers in chrome but not search params:

search
URLSearchParams
paramsMap
Map(0)
size(0)
__proto__
Map
[[Entries]]
Array(0)
length(0)

If I don't set params and manually write param into search option like this: return new RequestOptions({ headers: headers, search: 'pageSize=6' }); it works

Upvotes: 1

Views: 2719

Answers (4)

Christophe Lallement
Christophe Lallement

Reputation: 2457

I've encounter same issue because I was not importing URLSearchParams.

import { URLSearchParams } from '@angular/http';

Without importing explicitly URLSearchParams it was compling fine but the parameters request were empty.

Also notice the RequestOptions property search is deprecated, You should use params :

RequestOptions({ headers: headers, params : myParams })

in place of

RequestOptions({ headers: headers, search : params })

The solution to use params.toString() is a good workaround since RequestOptionsArgs could also either a string or URLSearchParams :

export interface RequestOptionsArgs {
    url?: string | null;
    method?: string | RequestMethod | null;
    /** @deprecated from 4.0.0. Use params instead. */
    search?: string | URLSearchParams | {
        [key: string]: any | any[];
    } | null;
    params?: string | URLSearchParams | {
        [key: string]: any | any[];
    } | null;
    headers?: Headers | null;
    body?: any;
    withCredentials?: boolean | null;
    responseType?: ResponseContentType | null;
}

It avoid the issue by passing a string. In this case there is not point to use a URLSearchParams.

Upvotes: 10

Piotr Nowicki
Piotr Nowicki

Reputation: 21

Try using params.toString()

const params: URLSearchParams = new URLSearchParams();
params.set('_language', this.translate.currentLang);

return new RequestOptions({headers: headers, params: params.toString()});

Upvotes: 1

Alessandro Celeghin
Alessandro Celeghin

Reputation: 4199

The problem is here:

RequestOptions({ headers: headers, search: params });

because if I use a string like this

RequestOptions({ headers: headers, search: 'pageSize=6' });

it works and in chrome I see this RequestOptions:

{"method":null,"headers":{"Authorization":["Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkYW5pZWxlIiwiaXAiOiI3OS4xLjMzLjEzOCIsImV4cCI6MTQ5MTM4MDIyMn0.Z9Y2l7-VDE_Rd8jEqhZ2Sdpx-is5nBeRamtkYrRtt_4oGWXomkhg6-ig87BL0PI5kL11sLf24lpytK8YDeiWMQ"]},"body":null,"url":null,"params":{"rawParams":"pageSize=6","queryEncoder":{},"paramsMap":{}},"withCredentials":null,"responseType":null}

If I use params my rawParams remains empty

Upvotes: 1

wuno
wuno

Reputation: 9875

Try to retrieve the data outside of the function so when the component loads it will exist before the Get Request is called.

Function To Set LocalStorageData

private get currentUser(): string {
      return localStorage.getItem('currentUser');
    }

Retrieve Data

myCurrentUser = JSON.parse(this. currentUser);

Get Request

private setDefaultPaymentMethod(payid: string) {
        const params: URLSearchParams = new URLSearchParams();
        params.set('currentUser', this.myCurrentUser);
        return this.http.get('Path/URL/End?point'
            { search: params })
            .map((res: Response) => res.json())
            .subscribe((res) => {
                console.log(res);
            });
    }

Upvotes: 1

Related Questions