如何在 Angular 中的 http GET 请求中传递多个参数?

Iti*_*dta 2 xmlhttprequest angular

我使用下面的方法在 http get 请求中传递多个参数,但它给了我一个错误 -

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(...);
Run Code Online (Sandbox Code Playgroud)

错误- 无法重新声明块作用域变量“params”

如果我更改名称,那么如何在 URL 中调用它?

作为一种解决方法,我考虑直接在 URL 中附加参数,如下所示 -

this.params1 = 'parameter1';
this.params2 = 'parameter2';
this.params3 = 'parameter3';
Run Code Online (Sandbox Code Playgroud)

http 请求 -

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

我收到这个错误 -

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.

为了检查 URL 是否正确附加,我单击了错误中的 url,它工作正常。

谁能帮我解决这个问题吗?

谢谢 !!

Mar*_*arc 6

可以发送参数:

const params = new HttpParams()
   .set('p1', 'one!')
   .set('para2', "two");
Run Code Online (Sandbox Code Playgroud)

this.httpClient.get<any>(yoururl,{params}) // {params} short form of {params:params}
Run Code Online (Sandbox Code Playgroud)

你的代码看起来不错,也许你有一个cors问题:什么是StaticSettings.BASE_URL?http 还是 https?还是相对网址?