角度,带有参数的Http GET? [英] Angular, Http GET with parameter?

查看:149
本文介绍了角度,带有参数的Http GET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何对这样的方法进行API调用:

I dont know how to make an API call to such a method:

[HttpGet]
[ActionName("GetSupport")]
public HttpResponseMessage GetSupport(int projectid)

因为它是GET但仍然有一个参数要传递,该怎么做? 会是这样吗?

Because it is GET but still got a parameter to pass, how to do this? Would it be something like this?

let headers = new Headers();
      headers.append('Content-Type', 'application/json');
      headers.append('projectid', this.id);

      this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers })

推荐答案

具有以下内容:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('projectid', this.id);
let params = new URLSearchParams();
params.append("someParamKey", this.someParamValue)

this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers, search: params })

当然,您需要将每个参数附加到params.与仅使用URL字符串将参数传递给请求相比,它提供了更多的灵活性.

Of course, appending every param you need to params. It gives you a lot more flexibility than just using a URL string to pass params to the request.

编辑(28.09.2017): Al-Mothafar 在评论中指出,search自Angular 4起已弃用,因此您应使用params

EDIT(28.09.2017): As Al-Mothafar stated in a comment, search is deprecated as of Angular 4, so you should use params

编辑(02.11.2017):如果您正在使用新的HttpClient,则现在有HttpParams,其外观和用法如下:

EDIT(02.11.2017): If you are using the new HttpClient there are now HttpParams, which look and are used like this:

let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams

然后基本上以相同的方式将参数添加到请求中:

And then add the params to the request in, basically, the same way:

this.http.get(url, {headers: headers, params: params}); 
//No need to use .map(res => res.json()) anymore

HttpParams 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆