Mands
Mands

Reputation: 221

How to pass query params in url in a HTTP post request in Angular

This is how i am passing the params to my http post request in Postman. And it 's status is ok 200. enter image description here

i am trying to do it from angular code like this.

getInfo() {
        const params = [];
        params.push({code: 'checkinFrom', name: '2019-02-01'});
        params.push({code: 'checkinTo', name: '2019-10-01'});
        params.push({code: 'room_type_ids', name: [2]});
        
        console.log(params);
        return this.service.post(environment.url + 'v1/transactions/demand/price-info',  params);
}

This is my post method in Service class.

 post(path, body): Observable<any> {
        return this.http
            .post(
                path,
                body,
                {
                    headers: Service.setHeaders([])
                }
            )
            .pipe(
                catchError(error => {
                    throw error;
                }),
                map((res: Response) => res)
            );
    }

But in Angular front end when i am trying to send the params it gives an error like 422 (Unprocessable Entity). How i want to pass the params?

Upvotes: 2

Views: 5163

Answers (1)

Brandon Avilan
Brandon Avilan

Reputation: 56

You could try to put them in the post method like the headers, it would be something like this

post(path, body): Observable<any> {
    return this.http
        .post(
            path,
            body,
            {
                headers: Service.setHeaders([]),
                params: {
                  param1: param1Value,
                  param2: param2Value,
                  ...
                },

            }
        )
        .pipe(
            catchError(error => {
                throw error;
            }),
            map((res: Response) => res)
        );
}

If you want use params as an array you must transform your array of objects to object of objects. Visit How do I convert array of Objects into one Object in JavaScript?

I hope I've helped

Upvotes: 3

Related Questions