问题描述
大家好我在Angular上创建HTTP请求,但我不知道如何向其添加url参数(查询字符串)。
Hi guys I'm creating a HTTP request on Angular, but I do not know how to add url arguments (query string) to it.
this.http.get(StaticSettings.BASE_URL).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
现在我的StaticSettings.BASE_URL就像一个没有查询的网址字符串如:但我希望它是
Now my StaticSettings.BASE_URL is something like a url with no query string like: http://atsomeplace.com/ but I want it to be http://atsomeplace.com/?var1=val1&var2=val2
哪里var1和var2适合我的Http请求对象?我想像对象一样添加它们。
Where var1, and var2 fit on my Http request object? I want to add them like an object.
{
query: {
var1: val1,
var2: val2
}
}
然后只是Http模块完成工作将其解析为URL查询字符串。
and then just the Http module do the job to parse it into URL query string.
推荐答案
方法允许您设置 params 在它的选项中。
您可以通过导入 。
You can configure it by importing the HttpClientModule from the @angular/common/http package.
import {HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [ BrowserModule, HttpClientModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
之后你可以注入 HttpClient 并使用它来执行请求。
After that you can inject the HttpClient and use it to do the request.
import {HttpClient} from '@angular/common/http'
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor(private httpClient: HttpClient) {
this.httpClient.get('/url', {
params: {
appid: 'id1234',
cnt: '5'
},
observe: 'response'
})
.toPromise()
.then(response => {
console.log(response);
})
.catch(console.log);
}
}
你可以找到一个工作示例。
You can find a working example here.
对于版本4之前的角度版本,您可以使用 Http 服务执行相同操作。
For angular versions prior to version 4 you can do the same using the Http service.
Http.get method接受一个实现的对象第二个参数。
The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.
该对象的搜索字段可用于设置字符串或对象。
The search field of that object can be used to set a string or a URLSearchParams object.
例如:
// Parameters obj-
let params: URLSearchParams = new URLSearchParams();
params.set('appid', StaticSettings.API_KEY);
params.set('cnt', days.toString());
//Http request-
return this.http.get(StaticSettings.BASE_URL, {
search: params
}).subscribe(
(response) => this.onGetForecastResult(response.json()),
(error) => this.onGetForecastError(error.json()),
() => this.onGetForecastComplete()
);
Http 类的文档有更多细节。它可以在和一个工作示例中找到。
The documentation for the Http class has more details. It can be found here and an working example here.
这篇关于如何将url参数(查询字符串)传递给Angular上的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!