The HttpClient methods allow you to set the params in it's options.
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 {}
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);
}
}
For angular versions prior to version 4 you can do the same using the Http service.
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.
An example:
// 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()
);
The documentation for the Http class has more details. It can be found here and an working example here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…