How I can pass url arguments to a HTTP request on Angular?

Forums AngularHow I can pass url arguments to a HTTP request on Angular?
Staff asked 3 years ago

Answers (1)

Add Answer
Umang Ramani Marked As Accepted
Staff answered 3 years ago

The 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()
);

 

 

Subscribe

Select Categories