我想从一个Angular组件触发HTTP请求,但我不知道如何向它添加URL参数(查询字符串)。

this.http.get(StaticSettings.BASE_URL).subscribe(
  (response) => this.onGetForecastResult(response.json()),
  (error) => this.onGetForecastError(error.json()),
  () => this.onGetForecastComplete()
)

现在是我的静态设置。BASE_URL就像一个没有查询字符串的URL: http://atsomeplace.com/,但我想让它像http://atsomeplace.com/?var1=val1&var2=val2

如何添加var1,和var2到我的HTTP请求对象作为对象?

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

然后只有HTTP模块将其解析为URL查询字符串。


当前回答

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

其他回答

如果您计划发送多个参数。

组件

private options = {
  sort:   '-id',
  select: null,
  limit:  1000,
  skip:   0,
  from:   null,
  to:     null
};

constructor(private service: Service) { }

ngOnInit() {
  this.service.getAllItems(this.options)
    .subscribe((item: Item[]) => {
      this.item = item;
    });
}

服务

private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
constructor(private http: Http) { }

getAllItems(query: any) {
  let params: URLSearchParams = new URLSearchParams();
  for(let key in query){
    params.set(key.toString(), query[key]);
  }
  this.options.search = params;
  this.header = this.headers();

继续你的http请求,就像@ethemsulan做的那样。

服务器端路由

router.get('/api/items', (req, res) => {
  let q = {};
  let skip = req.query.skip;
  let limit = req.query.limit;
  let sort  = req.query.sort;
  q.from = req.query.from;
  q.to = req.query.to;

  Items.find(q)
    .skip(skip)
    .limit(limit)
    .sort(sort)
    .exec((err, items) => {
      if(err) {
        return res.status(500).json({
          title: "An error occurred",
          error: err
        });
      }
      res.status(200).json({
        message: "Success",
        obj:  items
      });
    });
});
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);

在最新的Angular 7/8中,你可以使用最简单的方法:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

角6

你可以通过使用params传入get调用所需的参数:

this.httpClient.get<any>(url, { params: x });

其中x = {property: "123"}。

对于记录“123”的api函数:

router.get('/example', (req, res) => {
    console.log(req.query.property);
})

您可以使用官方文档中的Url参数。

操作:这个httpClient。得到(这个。火,(params: new HttpParams()。集合(“noCover”,noCover)