httpangulartypescript

How to pass url arguments (query string) to a HTTP request on Angular?


I would like to trigger HTTP request from an Angular component, 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()
)

Now my StaticSettings.BASE_URL is like a URL without query string like: http://atsomeplace.com/ but I want it to be like http://atsomeplace.com/?var1=val1&var2=val2

How to add var1, and var2 to my HTTP request object as an object?

{
  query: {
    var1: val1,
    var2: val2
  }
}

and then just the HTTP module does the job to parse it into URL query string.


Solution

  • 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.