How to pass url arguments (query string) to a HTTP

2019-01-02 19:33发布

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

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

Where var1, and var2 fit on my Http request object? I want to add them like an object.

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

and then just the Http module do the job to parse it into URL query string.

9条回答
几人难应
2楼-- · 2019-01-02 20:29
import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
    var qStr = $.param(params); //<---YOUR GUY
    return this._http.get(this._adUrl+"?"+qStr)
      .map((response: Response) => <any[]> response.json())
      .catch(this.handleError);
}

provided that you have installed jQuery, I do npm i jquery --save and include in apps.scripts in angular-cli.json

查看更多
倾城一夜雪
3楼-- · 2019-01-02 20:32
import { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}

return this._http.get('http://url/login/' + email + '/' + password)
       .map((res: Response) => {
           return res.json();
        }).catch(this._handleError);
查看更多
回忆,回不去的记忆
4楼-- · 2019-01-02 20:32

You can use Url Parameters from the official documentation.

Example: this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })

查看更多
登录 后发表回答