How I can pass url arguments to a HTTP request on Angular?
Answers (1)
Add AnswerThe HttpClient methods allow you to configure the parameters in the options.
Import the HttpClientModule from the @angular/common/http package to configure it.
import {HttpClientModule} from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, HttpClientModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {}
Following that, you can inject the HttpClient and use it to execute 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 achieve the same thing with Angular versions prior to version 4 by utilizing the HTTP service.
As a second parameter, the HTTP. get function accepts an object that implements RequestOptionsArgs.
The object’s search field may be used to set a string or a URLSearchParams object.
An example:
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() );