2

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 !!

1
  • &parameter1: first ampersand is too much, but this is not the problem. Commented May 24, 2020 at 19:17

2 Answers 2

6

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Great !Thanks! It appended all the parameters correctly but I am still getting CORS error. How can I fix this ?
this is a second question ;-) ok. I need the infos: What is StaticSettings.BASE_URL? http or https? Or a relative url?
It's been resolved !! Found a solution ! Thanks anyways !! and I was making a request to google places API
0

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 ! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.