How to pass multiple parameters in http GET request in Angular?

Viewed 12735

I am using below method to pass multiple parameters in http get request but it is giving me an error -

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

ERROR - Cannot redeclare block-scoped variable 'params'

If I change the name then how can I call it inside the URL ?

As a workaround, I thought of appending the parameters directly in the URL instead as follows-

this.params1 = 'parameter1';
this.params2 = 'parameter2';
this.params3 = 'parameter3';

http request -

return this.http.get('URL/json?'+'&parameter1='+this.params1+'&parameter2='+this.params2+'&parameter3='+this.params3)

I got this ERROR -

Access to XMLHttpRequest at 'URL/json?'+'&parameter1='+this.params1+'&parameter2='+this.params2+'&parameter3='+this.params3' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

To check if the URL got appended correctly I clicked on the url in the error and it worked properly.

Can anyone please help me resolve this?

Thanks !!

2 Answers

Params can be sent:

const params = new HttpParams()
   .set('p1', 'one!')
   .set('para2', "two");

and

this.httpClient.get<any>(yoururl,{params}) // {params} short form of {params:params}

Your code looks good, perhaps you have a cors problem: What is StaticSettings.BASE_URL? http or https? Or a relative url?

The first part of the question ( i.e. to pass multiple parameters ) was solved . Thanks to @Marc who answered this question.

I thought the problem was due to the way I had appended the params but it was a CORS issue. To fix it, I added https://cors-anywhere.herokuapp.com before the url in the http request as -

https://cors-anywhere.herokuapp.com/URL & it worked ! :)

Related